裁剪帶圓環的圓形的圖片步驟

裁剪帶圓環的圓形的圖片步驟:spa

1.加載圖片orm

    UIImage *image = [UIImage imageNamed:@"dst2"];對象

2.開啓圖形上下文對象begin(後須要關閉end)圖片

由於圓環上下文的size比圖片大一些。ip

    CGFloat margin = 5;get

    CGSize ctxSize = CGSizeMake(image.size.width +2*margin , image.size.height + 2*margin);it

    UIGraphicsBeginImageContextWithOptions(ctxSize, YES, 0);io

3.獲取開啓的上下文對象im

    CGContextRef ctx = UIGraphicsGetCurrentContext();margin

    

4.肯定圓形的圓環的半徑與圓心

    CGPoint centerP = CGPointMake(ctxSize.width/2, ctxSize.height/2);

    CGFloat radius = MIN(image.size.width, image.size.height)/2;

5.裁減圓形和繪製圓環。

    /* ************** 建立一個圓環*************/

    UIBezierPath *pathLine = [UIBezierPath bezierPathWithArcCenter:centerP radius:radius startAngle:0 endAngle:2*M_PI clockwise:YES];

    CGContextSetLineWidth(ctx, 10);

    [[UIColor redColor]set];

    CGContextAddPath(ctx, pathLine.CGPath);

    CGContextDrawPath(ctx, kCGPathStroke);

    /* ************** 建立一個圓環*************/

    /***************** 裁減圓形 ********************/

    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:centerP radius:radius startAngle:0 endAngle:2*M_PI clockwise:YES];

    CGContextAddPath(ctx, path.CGPath);

    CGContextClip(ctx);

    /***************** 裁減圓形 ********************/

(注意:圓環在前,圓形在後,不然看不到圓環)

6.繪製圖片

    [image drawAtPoint:CGPointMake(margin, margin)];

    

7.獲取裁剪後圖片

    UIImage *getImage = UIGraphicsGetImageFromCurrentImageContext();

///////此時判斷是否須要對圖片進行適應屏幕的裁減。(好比長寬不等圖片可能會出現壓縮,須要裁剪成方形)

 //7.截取圖片(以前須要先將圖片添加到圖形上下文中,而後獲取到再截取)

    CGFloat x;
   
CGFloat y;
   
CGFloat w;
   
CGFloat h;
   
//a.當是豎屏照片時
   
if (getImage.size.height >=getImage.size.width) {
       
        x =
0;
        y = (getImage.size.height
- 2*radius)/2;
       
    }else{
       
//b.當時橫屏照片時
        y =
0;
        x = (getImage.size.width
- 2*radius)/2;
    }
   
    w =
2*radius;
    h = w;
   
   
//爲保證圖片的正確顯示,乘以屏幕縮放比
   
CGFloat scale = [UIScreen mainScreen].scale;
    x *= scale;
    y *= scale;
    w *= scale;
    h *= scale;
   
//截取  CG開頭C語言。不用*
   
CGImageRef imageRef = CGImageCreateWithImageInRect(getImage.CGImage, CGRectMake(x, y, w, h));
   
   
//轉換格式

    getImage = [UIImage imageWithCGImage:imageRef];

8.關閉以前開啓的上下文

    UIGraphicsEndImageContext();

9.給imageView的image賦值。

相關文章
相關標籤/搜索