UIImage用另一个图像填充透明部分 [英] UIImage fill transparent part with another image

查看:195
本文介绍了UIImage用另一个图像填充透明部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用iOS中的另一张图片填充图片的透明部分.

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

我已经尝试过使用UIGraphicsContext进行某些操作,但是由于之前从未使用过,所以无法正常工作.

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

这是图片:

我尝试过的一些代码:

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

推荐答案

这是我的处理方式:

您可以通过执行以下操作来制作圆形的剪切路径:

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

这篇关于UIImage用另一个图像填充透明部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆