How erase part of UIImage

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

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

  • iPhone Objective C: How to get a pixel's color of the touched point on an UIImageView?
  • iPhone X how to handle View Controller inputAccessoryView?
  • JSON or SOAP (XML)?
  • Tried to obtain the web lock from a thread other than the main thread or the web thread. Crashing now
  • Sharing Image on instagram in ios
  • SDWebImage process images before caching
  • - (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

    2 Solutions Collect From Internet About “How erase part of UIImage”

    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.

    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);