您的位置:首页 > 移动开发 > IOS开发

创建带文字的图片

2017-08-30 14:36 141 查看

创建带文字的图片

-(UIImage *)addText:(UIImage *)img text:(NSString *)text1
{
//上下文的大小
int w = img.size.width;
int h = img.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();//创建颜色
//创建上下文
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 44 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);//将img绘至context上下文中
CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 0.5);//设置颜色
char* text = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];
CGContextSelectFont(context, "Georgia", 20, kCGEncodingMacRoman);//设置字体的大小
CGContextSetTextDrawingMode(context, kCGTextFill);//设置字体绘制方式
CGContextSetRGBFillColor(context, 1, 1, 1, 1);//设置字体绘制的颜色
if([text1 intValue]>=10){
CGContextShowTextAtPoint(context, w/2-strlen(text)*5, h/2-strlen(text)*4+2, text, strlen(text));//设置字体绘制的位置h/2-strlen(text)*4
}else{
CGContextShowTextAtPoint(context, w/2-strlen(text)*5, h/2-strlen(text)*4-2, text, strlen(text));//设置字体绘制的位置h/2-strlen(text)*4
}
//Create image ref from the context
CGImageRef imageMasked = CGBitmapContextCreateImage(context);//创建CGImage
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:imageMasked];//获得添加水印后的图片
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息