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

Mon*_*ish 6 objective-c slice uiimage 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];
Run Code Online (Sandbox Code Playgroud)

但它对我不起作用

请帮我。提前致谢。

Dip*_*ara 4

您正在使用函数,请- (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];
Run Code Online (Sandbox Code Playgroud)

迅速

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)
Run Code Online (Sandbox Code Playgroud)

互联网解决方案

使用以下函数也可以实现相同的结果。

Objective-C

UIImage *stretchedImage = [image resizableImageWithCapInsets:
                 UIEdgeInsetsMake(50, 50, 0, 50)];
Run Code Online (Sandbox Code Playgroud)

迅速

var stretchedImage = image?.resizableImage(withCapInsets: UIEdgeInsets(top: 50, left: 50, bottom: 0, right: 50), resizingMode: .stretch) 
Run Code Online (Sandbox Code Playgroud)

注意:使可拉伸图像尽可能小,否则较小的图像容器(ImageView、Button 等)将无法正确拉伸。您可以减少现有图像的高度和宽度。