UIImage fill transparent part with another image

我们两清 提交于 2019-12-20 04:04:25

问题


I would like to fill the transparent part of an image with another image in iOS.

I have tried some stuff with UIGraphicsContext, but I can't get it working because I've never used that before.

Here is the image:

Some code I tried:

UIImageView *v = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 70, 70)];

UIGraphicsBeginImageContextWithOptions(v.frame.size, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// beach image
UIImage *img = [UIImage imageNamed:@"zivogosce_camping_05.jpg"];
//[img drawInRect:CGRectMake(2, 0, 12, 12)];

UIImage *annotationImg = [UIImage imageNamed:@"custom_annotation"];
[annotationImg drawAtPoint:CGPointMake(0, 0)];

CGContextSetFillColorWithColor(context, [[UIColor colorWithPatternImage:img] CGColor]);
CGContextFillRect(context, CGRectMake(0, 0, 50, 50));


CGContextDrawImage(context, CGRectMake(0, 0, v.frame.size.width, v.frame.size.height), [annotationImg CGImage]);



UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

[v setImage:newImage];

UIGraphicsEndImageContext();

But images don't fit well...


回答1:


Here's how I would do it:

You can make a clipping path in the shape of the circle by doing something like this:

CGContextSaveGState(context);
CGRect circleRect = CGRectMake(circleCenter.x - radius, circleCenter.y - radius, radius * 2.0, radius * 2.0);
CGContextAddEllipseInRect (context, circleRect);
CGContextClip(context);

// ... do whatever you need to in order to draw the inner image ...

CGContextRestoreGState(context);

// ... draw the transparent png ...

Setting a clipping path will cause drawing to only happen within the path. When you restore the state, it removes the clipping path (or rather sets it back to its previous value which is usually allowing it to draw to the entire canvas).



来源:https://stackoverflow.com/questions/22642136/uiimage-fill-transparent-part-with-another-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!