简体   繁体   English

iOS使UIImage的一部分透明化

[英]iOS make part of an UIImage transparent

I have an UIImage where part of it has been selected by the user to clear out (make transparent). 我有一个UIImage,其中部分内容被用户选中以清除(透明)。 To make the selection I used NSBezierPath. 为了进行选择,我使用了NSBezierPath。

How can I clear/make transparent part of an UIImage in iOS? 如何在iOS中清除/制作UIImage的透明部分?

First, I assume you have a UIBezierPath (iOS), not an NSBezierPath (Mac OS X). 首先,我假设您有一个UIBezierPath(iOS),而不是NSBezierPath(Mac OS X)。

To do this, you will need to use core graphics, creating an image context, drawing the UIImage into that context, and then clearing the region specified by the NSBezierPath. 为此,您需要使用核心图形,创建图像上下文,将UIImage绘制到该上下文中,然后清除NSBezierPath指定的区域。

// Create an image context containing the original UIImage.
UIGraphicsBeginImageContext(originalImage.size);
[originalImage drawAtPoint:CGPointZero];

// Clip to the bezier path and clear that portion of the image.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddPath(context,bezierPath.CGPath)
CGContextClip(context);
CGContextClearRect(context,CGRectMake(0,0,originalImage.size.width,originalImage.size.height);

// Build a new UIImage from the image context.
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Swift4 solution from landweber 's above answer: 来自landweber上面的答案的Swift4解决方案:

UIGraphicsBeginImageContext(image!.size)
image!.draw(at: CGPoint.zero)
let context:CGContext = UIGraphicsGetCurrentContext()!;
let bez = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 10, height: 10))
context.addPath(bez.cgPath)
context.clip();
context.clear(CGRect(x: 0,y: 0,width: image!.size.width,height: image!.size.height));
let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!;
UIGraphicsEndImageContext();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM