图片圆角显示(二)

以前写过一篇文章:图片圆角显示,现在将提供另一种将图片转成圆角的方法。

 

static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)
{
    float fw, fh;
    if (ovalWidth == 0 || ovalHeight == 0) {
		CGContextAddRect(context, rect);
		return;
    }
    
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGContextScaleCTM(context, ovalWidth, ovalHeight);
    fw = CGRectGetWidth(rect) / ovalWidth;
    fh = CGRectGetHeight(rect) / ovalHeight;
    
    CGContextMoveToPoint(context, fw, fh / 2);  // 右下角
    CGContextAddArcToPoint(context, fw, fh, fw / 2, fh, 2);  // 右上角
    CGContextAddArcToPoint(context, 0, fh, 0, fh / 2, 2); // 左上角
    CGContextAddArcToPoint(context, 0, 0, fw / 2, 0, 2); // 左下角
    CGContextAddArcToPoint(context, fw, 0, fw, fh / 2, 2); // 右下角
    
    CGContextClosePath(context);
    CGContextRestoreGState(context);
}

+ (id) createRoundedRectImage:(UIImage *)image size:(CGSize)size
{
    int w = size.width;
    int h = size.height;
    
    UIImage *img = image;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGRect rect = CGRectMake(0, 0, w, h);
    
    CGContextBeginPath(context);
    addRoundedRectToPath(context, rect, 10, 10);
    CGContextClosePath(context);
    CGContextClip(context);
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return [UIImage imageWithCGImage:imageMasked];
}

 

示例图:


你可能感兴趣的:(ios,iPhone,圆角)