0

I have an jpg Image with a round object in a rect and want to make the envoirement of the round object transparent...

Example

(Remove red area in this example)

With the help of this iOS make part of an UIImage transparent and "UIBezierPath bezierPathWithOvalInRect" i've got a little success, but this make a path around my object, and I need to invert it, to make the outside and not the inside of the path transparent..

Im not shure where I have to change my code to get the right result..

Here is my code:

//BezierPath
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 100, 100)];  

// Create an image context containing the original UIImage.
UIGraphicsBeginImageContext(_imgTemp.image.size);
[_imgTemp.image 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,self._imgTemp.image.size.width,self._imgTemp.image.size.height));

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

Anybody got the resolving?

Community
  • 1
  • 1
Jones123
  • 249
  • 3
  • 8

1 Answers1

9

To only draw within the black circle you should move [_imgTemp.image drawAtPoint:CGPointZero]; to after CGContextClip(context); and then remove the CGContextClearRect( ... ) call entirely:

//BezierPath
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 100, 100)];  

// Create an image context containing the original UIImage.
UIGraphicsBeginImageContext(_imgTemp.image.size);

// Clip to the bezier path and clear that portion of the image.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddPath(context,bezierPath.CGPath);
CGContextClip(context);

// Draw here when the context is clipped
[_imgTemp.image drawAtPoint:CGPointZero];

// Build a new UIImage from the image context.
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self._imgTemp.image = newImage;
David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205
  • It's possible to clip the current context to a UIBezierPath with `[bezierPath addClip]`, so you don't have to fiddle with `CGContextRef` directly. – Cowirrie Apr 11 '12 at 06:33