如何在 iOS 中对图像进行切片和拉伸

How to slicing image and stretchable in iOS

我需要拉伸图像左右中心半圆保持原样。中心还需要半个圆圈

我试过切片概念,也试过下面的代码

UIImage *image = self.imgBGBottom.image;
CGFloat capWidth =  floorf(image.size.width / 2) - 50;
CGFloat capHeight =  0;
UIImage *capImage = [image resizableImageWithCapInsets:
                     UIEdgeInsetsMake(capHeight, capWidth, capHeight, capWidth)];

[self.imgBGBottom setImage:capImage];

但它对我不起作用

请帮助我。提前致谢。

试试这个

UIImage *image = self.imgBGBottom.image;
CGFloat capWidth =  floorf(image.size.width / 2) - 50;
CGFloat capTop =  50;  //the value is determined by the half circle height,i guess it is 50 height
CGFloat capBottom = 0;
UIImage *capImage = [image resizableImageWithCapInsets:
                             UIEdgeInsetsMake(capHeight, capTop, capBottom, capWidth)];

[self.imgBGBottom setImage:capImage];

您正在使用函数,请使用 - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight 而不是 - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets

按照以下代码所述设置左上角的上限以拉伸图像。

Objective-C

UIImage *image = [UIImage imageNamed:@"test"];

CGFloat capTop =  50;  // top cap to keep half round as is
CGFloat capLeft = 5; // To repeat it or stretch equally.
UIImage *capImage = [image stretchableImageWithLeftCapWidth:capLeft topCapHeight:capTop];

Swift

let image =  UIImage(named: "stretchableImage")

let capTop:Int =  50;  // top cap to keep half round as is
let capLeft:Int = 5; // To repeat it or stretch equally.
let capImage = image?.stretchableImage(withLeftCapWidth: capLeft, topCapHeight: capTop)

Alternet 解决方案

使用下面的函数也可以得到同样的结果。

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) 

Note : Keep stretchable image as small as possible otherwise it will not stretch properly with smaller image container(ImageView, Button etc.). You can reduce height & width of your existing image.