1. 程式人生 > >iOS 畫圓圖片的幾種方法

iOS 畫圓圖片的幾種方法

方法一:

self.cycleImv= [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 50, 50)];

[self.view addSubview:self.cycleImv];

// 為圖片切圓

self.cycleImv.layer.masksToBounds = YES;

self.cycleImv.layer.cornerRadius = self.cycleImv.frame.size.width / 2.0;

// 為圖片新增邊框,根據需要設定邊框

self.cycleImv.layer.borderWidth = 2.0;//邊框的寬度

self.cycleImv.layer.borderColor = [UIColor redColor].CGColor;//邊框的顏色

方法二:

- (void)drawRect:(CGRect)rect

{

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.cycleImv.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:self.cycleImv.bounds.size];

CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];

//設定大小

maskLayer.frame = self.cycleImv.bounds;

//設定圖形樣子

maskLayer.path = maskPath.CGPath;

self.cycleImv.layer.mask = maskLayer;

}

方法三:

將網路圖片裁剪為圓形,首先建立一個UIImage分類UIImage+Extension,一個UIImageView分類UIImageView+CircularImv。

UIImage+Extension.h檔案

#[email protected] UIImage (Extension)

- (UIImage *)circleImage;

@end

UIImage+Extension.m檔案

#import "UIImage+Extension.h"

@implementation UIImage (Extension)

- (UIImage *)circleImage

{

// 開始圖形上下文,NO代表透明

UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);

// 獲得圖形上下文

CGContextRef ctx = UIGraphicsGetCurrentContext();

// 設定一個範圍

CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);

// 根據一個rect建立一個橢圓

CGContextAddEllipseInRect(ctx, rect);

// 裁剪

CGContextClip(ctx);

// 將原照片畫到圖形上下文

[self drawInRect:rect];

// 從上下文上獲取剪裁後的照片

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

// 關閉上下文

UIGraphicsEndImageContext();

return newImage;

}

@end

 

使用了SDWebImage載入網路圖片,所以加上UIImageView+WebCache.h標頭檔案。

UIImageView+CircularImv.h檔案

#[email protected] UIImageView (CircularImv)

- (void)setCircularImvURL:(NSString *)imageUrl holderImageName:(NSString *)imageName;

@end

UIImageView+CircularImv.m檔案

#import "UIImageView+CircularImv.h"

#import "UIImageView+WebCache.h"

#import "UIImage+Extension.h"

@implementation UIImageView (CircularImv)

- (void)setCircularImvURL:(NSString *)imageUrl holderImageName:(NSString *)imageName

{

//佔位圖片,當URL上下載的圖片為空,就顯示該圖片

UIImage *placeholder = [[UIImage imageNamed:imageName] circleImage];

[self sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:placeholder completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

//當圖片下載完會來到這個block,執行以下程式碼

self.image = image ? [image circleImage] : placeholder;

}];

}

@end