问题
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