本文實例為大家分享了iOS將圖片裁剪成圓形的具體代碼,供大家參考,具體內容如下
原圖:
圓形圖片裁剪效果:
裁剪成帶邊框的圓形圖片:
核心代碼:
#import <UIKit/UIKit.h>@interface UIImage (image)/** * 生成一張圓形圖片 * * @param image 要裁剪的圖片 * * @return 生成的圓形圖片 */+ (UIImage *)imageWithClipImage:(UIImage *)image;/** * 生成一張帶有邊框的圓形圖片 * * @param borderW 邊框寬度 * @param borderColor 邊框顏色 * @param image 要添加邊框的圖片 * * @return 生成的帶有邊框的圓形圖片 */+ (UIImage *)imageWithBorder:(CGFloat)borderW color:(UIColor *)borderColor image:(UIImage *)image;@end
#import "UIImage+image.h"@implementation UIImage (image)+ (UIImage *)imageWithClipImage:(UIImage *)image{+ //1.開啟跟原始圖片一樣大小的上下文 UIGraphicsBeginImageContextWithOptions(image.size, NO, 0); //2.設置一個圓形裁剪區域 //2.1繪制一個圓形 UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)]; //2.2.把圓形的路徑設置成裁剪區域 [path addClip];//超過裁剪區域以外的內容都給裁剪掉 //3.把圖片繪制到上下文當中(超過裁剪區域以外的內容都給裁剪掉) [image drawAtPoint:CGPointZero]; //4.從上下文當中取出圖片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); //5.關閉上下文 UIGraphicsEndImageContext(); return newImage;}+ (UIImage *)imageWithBorder:(CGFloat)borderW color:(UIColor *)borderColor image:(UIImage *)image{ //1.開啟一個上下文 CGSize size = CGSizeMake(image.size.width + 2 * borderW, image.size.height + 2 * borderW); UIGraphicsBeginImageContextWithOptions(size, NO, 0); //2.繪制大圓,顯示出來 UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)]; [borderColor set]; [path fill]; //3.繪制一個小圓,把小圓設置成裁剪區域 UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)]; [clipPath addClip]; //4.把圖片繪制到上下文當中 [image drawAtPoint:CGPointMake(borderW, borderW)]; //5.從上下文當中取出圖片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); //6.關閉上下文 UIGraphicsEndImageContext(); return newImage;}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答