iOS 截屏-在图片上绘制文字

截屏

- (UIImage *)screenshot:(UIView *)view
{
    CGFloat scale = [[UIScreen mainScreen] scale];
    UIImage *screenshot;
    
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, scale);
    {
        if(UIGraphicsGetCurrentContext() == nil)
        {
            NSLog(@"UIGraphicsGetCurrentContext is nil. You may have a view (%@) with no really frame (%@)", [view class], NSStringFromCGRect(view.frame));
        }
        else
        {
            [view.layer renderInContext:UIGraphicsGetCurrentContext()];
            
            screenshot = UIGraphicsGetImageFromCurrentImageContext();
        }
    }
    UIGraphicsEndImageContext();
    
    return screenshot;
}

在图片上绘制文字

//在图片上绘制文字
+(UIImage *)DrawText:(NSString *)text forImage:(UIImage *)image{
    
    CGSize size = CGSizeMake(image.size.width,image.size.height ); // 画布大小
    
    UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
    
    [image drawAtPoint:CGPointMake(0,0)];
    
    // 获得一个位图图形上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextDrawPath(context,kCGPathStroke);
    
    NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:30.f], NSForegroundColorAttributeName:[UIColor redColor]};
    
    //计算出文字的宽度 设置控件限制的最大size为图片的size
    CGSize textSize = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    
    // 画文字 让文字处于居中模式
    [text drawAtPoint:CGPointMake((size.width - textSize.width)/2,image.size.height - 40) withAttributes:attributes];
    
    // 返回绘制的新图形
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容