iOS在图片上添加文字或图片

Objective-C在图片上添加文字,请使用如下方法:


/**
 在图片上添加文字,只支持英文,如果想添加其他文字,请看下面的方法

 @param image  图片
 @param string 要添加的文字

 @return 新的图片
 */
-(UIImage *)addText:(UIImage *)image text:(NSString *)string
{
    //上下文的大小
    int w = image.size.width;
    int h = image.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();//创建颜色
    //创建上下文
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 44 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), image.CGImage);//将img绘至context上下文中
    CGContextSetRGBFillColor(context, 0.0, 1.0, 1.0, 1);//设置颜色
    char* text = (char *)[string cStringUsingEncoding:NSASCIIStringEncoding];
    CGContextSelectFont(context, "Georgia", 50, kCGEncodingMacRoman);//设置字体的大小
    CGContextSetTextDrawingMode(context, kCGTextFill);//设置字体绘制方式
    CGContextSetRGBFillColor(context, 255, 0, 0, 1);//设置字体绘制的颜色
    CGContextShowTextAtPoint(context, w/2-strlen(text)*5, h/2, text, strlen(text));//设置字体绘制的位置
    //Create image ref from the context
    CGImageRef imageMasked = CGBitmapContextCreateImage(context);//创建CGImage
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return [UIImage imageWithCGImage:imageMasked];//获得添加水印后的图片   
}


Objective-C在图片上添加图片,请使用如下方法:

/**
 在一张图片上添加logo或者水印;
 添加文字也可以这么做,让美工做一张文字图片即可
 warn 不支持jpg的图片
 
 @param image     原始的图片
 @param logoImage 要添加的logo

 @return 返回一张新的图片
 */
-(UIImage *)addImageLogo:(UIImage *)image text:(UIImage *)logoImage
{
    //原始图片的宽和高,可以根据需求自己定义
    CGFloat w = self.view.frame.size.width;
    CGFloat h = self.view.frame.size.height;
    //logo的宽和高,也可以根据需求自己定义
    CGFloat logoWidth = logoImage.size.width;
    CGFloat logoHeight = logoImage.size.height;
    //绘制
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 44 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), image.CGImage);
    //绘制的logo位置,可自己调整
    CGContextDrawImage(context, CGRectMake(w-logoWidth-10, 10, logoWidth, logoHeight), [logoImage CGImage]);
    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return [UIImage imageWithCGImage:imageMasked];
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值