简体   繁体   English

如何擦除UIImage的一部分

[英]How erase part of UIImage

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 kl94

The code is using quartz (iPhone's graphics engine) to clip the image. 该代码使用石英(iPhone的图形引擎)裁剪图像。 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". 这是获取“ erasePath”的方法。 Just pass the selected CGRect you want to crop as "cropRect" - 只需将要裁剪的选定CGRect传递为“ cropRect”-

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

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

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