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;
    
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容