这篇文章是在阅读了这篇与智能机器人聊天的文章总结出来的感觉对自己有用的方法,这里分享给大家,同时也作为自己的一个备忘吧。
有一张图片,刚开始时它是这样的:
然后我想要的图片是这样的:
和这样的:
要获得下面的两种图片的画就涉及到图片的渲染问题了,首先你得加入如下方法:
- (UIImage *)coloredImage:(UIImage *)image red:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpa:(CGFloat)alpa {
// 获取图片大小
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
// 创建位图绘图上下文
UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale);
// 获取位图绘图上下文并开始渲染操作
CGContextRef context = UIGraphicsGetCurrentContext();
[image drawInRect:rect];
CGContextSetRGBFillColor(context, red, green, blue, alpa);
CGContextSetBlendMode(context, kCGBlendModeSourceAtop);
CGContextFillRect(context, rect);
// 获取到绘图结果,结束位图绘图上下文并返回绘图结果
UIImage *resulet = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resulet;
}
上面的方法就是对传入的图片进行染色处理,相关的解释在代码里有。
图片渲染的辅助方法有了之后就是使用它了,代码但解释在代码注释里
- (void)viewDidAppear:(BOOL)animated {
NSString *imageName = @"MessageBubble";
UIImage *image = [UIImage imageNamed:imageName];
// 原始的图片
UIImageView *originView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 200, 48, 35)];
originView.image = image;
// 尖头向右的图片
UIImage *rightImage = [self coloredImage:image red:51/255.0 green:123/255.0 blue:214/255.0 alpa:1];
// 设置可拉伸区域
rightImage = [rightImage resizableImageWithCapInsets:UIEdgeInsetsMake(17, 21, 17.5, 26.5)];
UIImageView *rightImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 300, 320, 100)];
rightImageView.image = rightImage;
// 尖头向左的图片
UIImage *leftImage = [UIImage imageWithCGImage:image.CGImage scale:2.0 orientation:UIImageOrientationUpMirrored];
leftImage = [self coloredImage:leftImage red:255/255.0 green:0.0 blue:0.0 alpa:1];
leftImage = [leftImage resizableImageWithCapInsets:UIEdgeInsetsMake(17, 26.5, 17.5, 21)];
UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 450, 320, 100)];
leftImageView.image = leftImage;
// 将他们显示出来
[self.view addSubview:originView];
[self.view addSubview:rightImageView];
[self.view addSubview:leftImageView];
}
最终页面的显示效果如下图: