stretchableImageWithLeftCapWidth: topCapHeight:ht;

- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight;

这个方法是UIImage的一个对象方法,它的功能是创建一个左边和上边指定区域不可拉伸,的UIImage对象,第一个参数设置左边不可拉伸区域,第二个参数设置上边不可拉伸区域。这个方法通常用于创建可变宽度的按钮,并保持相同的圆角。

注意,通过此方法生成的UIImage对象在拉伸的时候拉伸的像素是设置的保留区域的后面的一个像素进行上下左右拉伸。假如leftCapWidth设为10,那么在向左拉伸的时候是左侧第11个像素所在那一列的像素进行向左平铺操作,如果topCapHeight设为20,那么在向下拉伸的时候是上面第21个像素所在一排的像素进行向下平铺操作,其余像素不会被平铺。

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImage* image0 = [UIImage imageNamed:@"searchbar_textfield_background"];
    UITextField* textField0 = [[UITextField alloc] init];
    textField0.background = image0;
    textField0.frame = CGRectMake(100, 100, image0.size.width, image0.size.height);
    [self.view addSubview:textField0];
    
    UIImage* image1 = [image0 stretchableImageWithLeftCapWidth:image0.size.width*0.5 topCapHeight:image0.size.height*0.5];
    UITextField* textField1 = [[UITextField alloc] init];
    textField1.background = image1;
    textField1.frame = CGRectMake(100, 300, 100, 30);
    [self.view addSubview:textField1];
}

效果如下:

原文地址:https://www.cnblogs.com/arthas/p/4655118.html