UIImage切圓角 - 優化

UIImage等比例縮放並切圓角

如題, 在網上找的代碼也是能夠用的, 可是問題是切成圓角時, 若是圖片自己不是正方形就會致使圖片變形,被壓縮或者拉伸. 今上午閱讀了那一段代碼, 而後本身寫出了任意長寬的圖片, 均可以等比例縮放並切割成圓角圖片, 默認切取圖像正中央的位置..net

[@interface](http://my.oschina.net/u/996807) UIImage (Extension)

///將UIImage圖像切成圓形的圖像, 指定寬度(邊長)
- (UIImage *)circleImageWithWidth:(double)width;

///切成圓形的圖片
- (UIImage *)cuttingCicleImageWithSize:(CGSize)size;

///縮放圖片尺寸
- (UIImage *)zoomImageToSize:(CGSize)size;

///按照比例縮放圖片, 原始圖片爲1, 參數(0~1)
- (UIImage *)zoomImageWithScale:(float)scale;

[@end](http://my.oschina.net/u/567204)

以下, 經過- (UIImage *)circleImageWithWidth:(double)width方法進行操做的,code

  • 第一步, 先將原始圖片進行等比例縮放;
  • 第二步, 截取等比縮放後正中央的正方形圖片;
  • 第三部, 將正方形圖像切割成圓角圖像.
@implementation UIImage (Extension)


///將UIImage圖像切成圓形的圖像, 指定寬度(邊長)
- (UIImage *)circleImageWithWidth:(double)width {
    
    // 計算一些變量, 供後面使用
    float screenScale = [[UIScreen mainScreen] scale];
    float scale = width / MIN(self.size.width, self.size.height);
    CGSize originalScaleSize = CGSizeMake(self.size.width * scale, self.size.height * scale);
    CGRect centerRange = CGRectOffset(CGRectMake(0, 0, width, width), (originalScaleSize.width-width)/2, (originalScaleSize.height-width)/2);
    

    
    // 調用方法將圖像縮放到指定的比例
    UIImage *newImage = [self zoomImageWithScale:scale];
    
    
    // 開始獲取圖片中間 正方形區域
    CGImageRef imageRef = newImage.CGImage;
    CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, CGRectMake(centerRange.origin.x, centerRange.origin.y, centerRange.size.width * screenScale, centerRange.size.height * screenScale));
    newImage = [UIImage imageWithCGImage:subImageRef];
    
    
    //切成圓角並返回圖像
    return [newImage cuttingCicleImageWithSize:CGSizeMake(width, width)];
}

///切成圓形的圖片
- (UIImage *)cuttingCicleImageWithSize:(CGSize)size {
    
    double screenScale = [[UIScreen mainScreen] scale];
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    
    UIGraphicsBeginImageContextWithOptions(size, NO, screenScale);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGContextAddEllipseInRect(ctx, rect);
    CGContextClip(ctx);
    [self drawInRect:rect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

///縮放圖片尺寸
- (UIImage *)zoomImageToSize:(CGSize)size {
    
    UIGraphicsBeginImageContextWithOptions(size, NO, [[UIScreen mainScreen] scale]);
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

///按照比例縮放圖片, 原始圖片爲1, 參數(0~1)
- (UIImage *)zoomImageWithScale:(float)scale {
    
    CGSize targetSize = CGSizeMake(self.size.width * scale, self.size.height * scale);
    return [self zoomImageToSize:targetSize];
}


[@end](http://my.oschina.net/u/567204)
相關文章
相關標籤/搜索