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

6

我需要将图像的右侧和左侧拉伸,同时保持中心半圆形不变。还需要在中心位置添加半圆形。

enter image description here

我尝试过切片概念,并且也尝试了下面的代码:

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];

但是对我来说它没有起作用。

请帮助我。提前谢谢。


@brainray,我需要两边都拉伸,但半圆保持不变。 - Monish
@DipenPanchasara:我尝试了您的答案,但它只会拉伸表单的左侧。 - Monish
@Monish 我已经更新了我的答案,请查看更新后的答案。 - Dipen Panchasara
@Monish 你试过了吗? - Dipen Panchasara
@DipenPanchasara:它只会拉伸一侧,我需要将半圆心的两侧都拉伸。 - Monish
显示剩余3条评论
2个回答

4

您正在使用- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets方法,请改用- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight方法。

按照以下代码设置上部和左部的拉伸参数来拉伸图片。

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)

备用解决方案

同样的结果也可以通过以下函数实现。

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等)正确拉伸。您可以减小现有图像的高度和宽度。

它不是向左和右侧拉伸,而是向中心拉伸。拉伸程度不是很大,因此很难辨认半圆如何变成半椭圆。 - Cy-4AH
@Cy-4AH 坐标拉伸图像的顶部和左侧根据您要拉伸的图像而异。我不确定您要拉伸哪个图像。如果您能提供一张图片或发布相关问题并分享链接,那就太好了。 - Dipen Panchasara

0

试试这个

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];

它不起作用了。图像中有重复的半圆。 - Monish

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接