iOS用戶頭像的圓形圖片裁剪常用方法

使用圖層剪切

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

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

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