iOS之帶有邊框的圓形圖片裁剪

來源:互聯網
上載者:User

標籤:

我們經常需要把一些不是圓形的圖片剪下成圓形後來使用,比如QQ頭像,微博頭像等都是圓形,那麼問題來了,該怎麼把一張不是圓形的圖片剪下成圓形呢?下面就是其中一種可以實現這種需求的方法: 具體實現思路:1.假設邊框寬度為BorderW2.開啟的圖片內容相關的尺寸就應該是原始圖片的寬高分別加上兩倍的BorderW,這樣開啟的目的是為了不讓原始圖片變形.3.在上下文上面添加一個圓形填充路徑.位置從0,0點開始,寬高和上下文尺寸一樣大.設定顏色為要設定的邊框顏色.4.繼續在上下文上面添加一個圓形路徑,這個路徑為裁剪路徑.它的x,y分別從BorderW這個點開始.寬度和高度分別和原始圖片的寬高一樣大.將繪製的這個路徑設為裁剪地區.5.把原始路徑繪製到上下文當中.繪製的位置和是裁剪地區的位置相同,x,y分別從border開始繪製.6.從上下文狀態當中取出圖片.7.關閉上下文狀態.   
 3.gif    載入要裁剪的圖片    UIImage *image = [UIImage imageNamed:@"阿狸頭像"];    0.設定邊框大小.    CGFloat borderW = 10;    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)];
    [[UIColor blueColor] set];    [path fill];    3.添加一個裁剪地區.    path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];    [path addClip];    4.把圖片繪製到裁剪地區當中.    [image drawAtPoint:CGPointMake(borderW, borderW)];    5.產生一張新圖片.    UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();    6.關閉上下文.    UIGraphicsEndImageContext(); 抽取分類方法: 根據傳入的圖片,產生一終帶有邊框的圓形圖片.borderW邊框寬度borderColor:邊框顏色image:要產生的原始圖片.+ (UIImage *)imageWithBorderW:(CGFloat)borderW borderColor:(UIColor *)color image:(UIImage *)image; + (UIImage *)imageWithBorderW:(CGFloat)borderW borderColor:(UIColor *)color 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)];
    [[UIColor blueColor] set];    [path fill];    3.添加一個裁剪地區.    path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];    [path addClip];    4.把圖片繪製到裁剪地區當中.    [image drawAtPoint:CGPointMake(borderW, borderW)];    5.產生一張新圖片.    UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();    6.關閉上下文.    UIGraphicsEndImageContext();
   
    return clipImage;
   
}     

iOS之帶有邊框的圓形圖片裁剪

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.