How erase part of UIImage

2020-03-07 05:33发布

问题:

Is there a way to erase the black background for that image

I've found this sample code found on this topic but i don't understand how it works

- (void)clipImage {
  UIImage *img = imgView.image;
  CGSize s = img.size;
  UIGraphicsBeginImageContext(s);
  CGContextRef g = UIGraphicsGetCurrentContext();
  CGContextAddPath(g,erasePath);
  CGContextAddRect(g,CGRectMake(0,0,s.width,s.height));
  CGContextEOClip(g);
  [img drawAtPoint:CGPointZero];
  imageView.image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
}

Maybe I'm in the wrong way.

Regards,
kl94

回答1:

The code is using quartz (iPhone's graphics engine) to clip the image. some details:

UIGraphicsBeginImageContext(s);
CGContextRef g = UIGraphicsGetCurrentContext();

You first need some sort of "target" to draw to. In graphics, that's usually called a context. Above, you tell the system a (bitmap) image context with given size is needed and then you get a reference to it.

CGContextAddPath(g,erasePath);
CGContextAddRect(g,CGRectMake(0,0,s.width,s.height));
CGContextEOClip(g);

Here, you provide a path to the context, and then clip the context. That's to say "only draw in these regions."

[img drawAtPoint:CGPointZero];

You draw the image in the new context. Only the clipped region will be drawn, so the rest is effectively erased.

imageView.image = UIGraphicsGetImageFromCurrentImageContext();

Now here, you just ask the system to give you back the image drawn in the context (target) you set up above

Note: this is a rough description, you might wanna look at the reference for each function to get more details.



回答2:

Here's how to get "erasePath". Just pass the selected CGRect you want to crop as "cropRect" -

CGMutablePathRef erasePath = CGPathCreateMutable();
CGPathAddRect(erasePath, NULL, cropRect);
CGContextAddPath(g,erasePath);