UIImage用另一个图像填充透明部分

我想用iOS中的另一个图像填充图像的透明部分。

我已经尝试了一些与UIGraphicsContext东西,但我不能得到它的工作,因为我从来没有使用过。

这是图像:

在这里输入图像说明

我试过一些代码:

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

但图像不适合…

以下是我将如何做到这一点:

你可以通过做这样的事情来做一个圆形的剪切path:

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

设置剪切path将使绘图只发生在path中。 当你恢复状态时,它将删除剪切path(或者将其设置回它以前的值,通常允许它绘制到整个canvas)。