Question

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:

enter image description here

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...

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top