您正在使用- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets
方法,请改用- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight
方法。
按照以下代码设置上部和左部的拉伸参数来拉伸图片。
Objective-C
UIImage *image = [UIImage imageNamed:@"test"];
CGFloat capTop = 50;
CGFloat capLeft = 5;
UIImage *capImage = [image stretchableImageWithLeftCapWidth:capLeft topCapHeight:capTop];
Swift
let image = UIImage(named: "stretchableImage")
let capTop:Int = 50;
let capLeft:Int = 5;
let capImage = image?.stretchableImage(withLeftCapWidth: capLeft, topCapHeight: capTop)
备用解决方案
同样的结果也可以通过以下函数实现。
Objective-C
UIImage *stretchedImage = [image resizableImageWithCapInsets:
UIEdgeInsetsMake(50, 50, 0, 50)];
Swift
var stretchedImage = image?.resizableImage(withCapInsets: UIEdgeInsets(top: 50, left: 50, bottom: 0, right: 50), resizingMode: .stretch)
注意:将可拉伸图像保持尽可能小,否则它将无法与较小的图像容器(ImageView、Button等)正确拉伸。您可以减小现有图像的高度和宽度。