iOS make part of an UIImage transparent

后端 未结 2 1508
情深已故
情深已故 2020-12-30 08:50

I have an UIImage where part of it has been selected by the user to clear out (make transparent). To make the selection I used NSBezierPath.

How can I clear/make tra

相关标签:
2条回答
  • 2020-12-30 09:18

    Swift4 solution from landweber's above answer:

    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();
    
    0 讨论(0)
  • 2020-12-30 09:31

    First, I assume you have a UIBezierPath (iOS), not an 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.

    // 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();
    
    0 讨论(0)
提交回复
热议问题