標籤:
這個是我自己在寫一個小實驗時,用到的功能。被我獨立抽取出來
+(UIImage *)capturImageWithUIView:(UIView *)view{ //開啟位元影像上下文 UIGraphicsBeginImageContext(view.bounds.size); //擷取當前位元影像 CGContextRef ctx = UIGraphicsGetCurrentContext(); //將視圖渲染到位元影像上 [view.layer renderInContext:ctx]; //擷取當前圖片 UIImage *currentImage = UIGraphicsGetImageFromCurrentImageContext(); //結束位元影像編輯 UIGraphicsEndImageContext(); return currentImage;}
下面這個是我隨手寫將方形圖片截成圓形圖片,並添加邊框。
+(UIImage *)cutCircleImageWithUIImage:(UIImage *)image WithBorderColor:(UIColor *)color withBorderWidth:(CGFloat)width{ CGRect imageRect = {{0,0},{image.size.width,image.size.height}}; //開啟位元影像上下文 UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0); //擷取當前位元影像 CGContextRef ctx = UIGraphicsGetCurrentContext(); //指定一個圓,將圓以外的部分刪掉 CGContextAddEllipseInRect(ctx, imageRect); CGContextClip(ctx); //將圖片添加進來 [image drawInRect:imageRect]; //添加邊框 CGContextAddEllipseInRect(ctx, imageRect); CGContextSetLineWidth(ctx, width); [color set]; CGContextStrokePath(ctx); //擷取當前圖片 UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext(); //結束位元影像編輯 UIGraphicsEndImageContext(); //將圖片返回 return screenImage;}
檔案放在雲端硬碟中:https://yunpan.cn/cP98wIjYCvQAZ (提取碼:30f5)
各位朋友如果有好的小功能想法,或者對My Code有建議都可以在評論裡留言。如果覺得我寫的還可以就請您點一下關注,若是可以請您一併關注我的微博:http://weibo.com/xiaopenguu 每次更新都會在微博中同步更新
感謝您的關注。
IOS開發:截取當前視圖