使用圖層剪切
//圖層處理
UIImage *image = [UIImage imageNamed:@"icon.png"];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 100, 100,100)];
imageView.image = image;
imageView.layer.masksToBounds = YES;
imageView.layer.cornerRadius = imageView.frame.size.width/2;
[self.view addSubview:imageView];
通過(guò)Quartz2D將圖形繪制出一張圓形圖片
通常的解決的辦法就是通過(guò)Quartz2D將圖形繪制出一張圓形圖片來(lái)進(jìn)行顯示。
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(50, 250, 100, 100)];
imageView2.image = [self imageWithSourceImage:image];
[self.view addSubview:imageView2];
}
- (UIImage *)imageWithSourceImage:(UIImage *)sourceImage {
UIGraphicsBeginImageContext(sourceImage.size);
//bezierPathWithOvalInRect方法后面?zhèn)鞯腞ect,可以看作(x,y,width,height),前兩個(gè)參數(shù)是裁剪的中心點(diǎn),后面兩個(gè)決定裁剪的區(qū)域是圓形還是橢圓.
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, sourceImage.size.width, sourceImage.size.height)];
//把路徑設(shè)置為裁剪區(qū)域(超出裁剪區(qū)域以外的內(nèi)容會(huì)自動(dòng)裁剪掉)
[path addClip];
//把圖片繪制到上下文當(dāng)中
[sourceImage drawAtPoint:CGPointZero];
//從上下文當(dāng)中生成一張新的圖片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//結(jié)束上下文
UIGraphicsEndImageContext();
//返回新的圖片
return newImage;
}