5

我想使用 UIBezierPath 之类的任何关闭路径在我的 iPhone 应用程序中裁剪图像。我知道可以使用矩形,但我想裁剪成不同的形状。就像我使用触摸制作一个形状并想裁剪该图像,这样它是如何可能的。任何建议或帮助。提前致谢。

4

3 回答 3

2

您可以使用 shapelayer 裁剪图像。为此,您必须创建一个路径,该路径将用作新图像的边框。你应该看看这个问题

CALayer* contentLayer = [CALayer layer];
[contentLayer setFrame:CGRectMake(0, 0, 80, 80)];
CAShapeLayer* mask = [CAShapeLayer layer];

CGMutablePathRef path = CGPathCreateMutable();

CGPathMoveToPoint(path, NULL, 10, 10);
CGPathAddLineToPoint(path, NULL, 10, 80);
CGPathAddLineToPoint(path, NULL, 80, 80);
CGPathAddLineToPoint(path, NULL, 80, 10);
mask.path = path;

[contentLayer setContents:(id)[[UIImage imageNamed:@"image.png"] CGImage]];
[contentLayer setMask:mask];          

[[self layer]addSublayer:contentLayer];

像这样的东西。

于 2012-08-21T07:52:14.237 回答
1

您可以使用掩码来完成此操作。您可以使用CGImageMaskCreate.

如果您需要示例:

知道为什么这个图像屏蔽代码不起作用吗?

http://mobiledevelopertips.com/cocoa/how-to-mask-an-image.html

于 2012-08-21T08:08:23.597 回答
0

// 在代码中使用:

  -(UIImage *)croppedImage

{
   UIImage *myImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();
[self.bezierPath closePath];

CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0,   0.0, 0.0);
_b_image = self.bg_imageview.image;

CGSize imageSize = _b_image.size;
CGRect imageRect = CGRectMake(0, 0, imageSize.width, imageSize.height);

UIGraphicsBeginImageContextWithOptions(imageSize, NO, [[UIScreen mainScreen] scale]);
[self.bezierPath addClip];
[_b_image drawInRect:imageRect];
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return croppedImage;}
于 2017-06-01T09:36:51.590 回答