UIImageView的图片拉伸

时间:2022-11-16 23:24:01
UIImageView的图片拉伸

iOS 8:UIView Stretching设置

使用小图片当变长输入框或类似QQ聊天文字背景效果时,需要拉伸图片。UIImage提供了三个可完成此任务的方法:

  • resizableImageWithCapInsets:
  • resizableImageWithCapInsets:resizingMode:
  • stretchableImageWithLeftCapWidth:topCapHeight:

第三个方法在iOS5中弃用。

在Storyboard或xib中拖入的控件都有Stretching属性,包含四个参数:X、Y、Width、Height。这些参数确定了进行拉伸的区域。

当X = Y = Width = Height = 1时,图片为原始大小。

若让X = Y = 0.5、Width = Height = 0,则按水平垂直位置的那个像素点进行拉伸,如图所示。

UIImageView的图片拉伸

另外,按钮背景图片的拉伸只能通过代码完成,属性检查器面板的Stretching设置无效。



对按钮背景图片的拉伸

在Interface Builder中,UIButton的backgroundImage不支持拉伸,准确的说是UIButton中的backgroundImage不能支持contentStretch属性,在IB中,不能单独对UIButton的backgroundImage设置contentStretch属性。这个属性可以在代码中设置,如下:

  1. UIImage *buttonBackgroundImage = [UIImage imageNamed:@"green-button.png"];
  2. UIImage *stretchedBackground = [buttonBackgroundImage stretchableImageWithLeftCapWidth:33 topCapHeight:0];
  3. [sendButton setBackgroundImage:stretchedBackground forState:UIControlStateNormal];

版权声明:本文为博主原创文章,未经博主允许不得转载。