现在的位置: 首页 > 综合 > 正文

画圆角图片的方法

2019年10月02日 ⁄ 综合 ⁄ 共 1553字 ⁄ 字号 评论关闭

1.   使用QuartzCore.framework

添加QuartzCore.framework,导入头文件 #import <QuartzCore/QuartzCore.h>

  [[imgView layer] setCornerRadius: 10];
  [[imgView layer] setMasksToBounds:YES];

2. 使用下面的方法:

static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)
{
    if (ovalWidth == 0 || ovalHeight == 0 ) {
        CGContextAddRect(context, rect);
        return;
    }
    
    float fw, fh;
    CGContextSaveGState(context);
    //change the corner size below...
    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.5);
    CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 2.5);
    CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 2.5);
    CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 2.5);
    
    CGContextClosePath(context);
    CGContextRestoreGState(context);
}

- (UIImage *)RoundRectImage:(UIImage *)image
{
    int width = image.size.width;
    int height = image.size.height;
    
    CGColorSpaceRef colorRef = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorRef, kCGImageAlphaPremultipliedLast);
    CGRect rect = CGRectMake(0, 0, width, height);
    
    CGContextBeginPath(context);
    addRoundedRectToPath(context, rect, 10, 10);
    CGContextClosePath(context);
    CGContextClip(context);
    
    CGContextDrawImage(context, rect, image.CGImage);
    CGImageRef imgMask = CGBitmapContextCreateImage(context);
    
    CGColorSpaceRelease(colorRef);
    CGContextRelease(context);
    
    return [UIImage imageWithCGImage:imgMask];
}

原贴:

http://www.cocoachina.com/bbs/read.php?tid=2275

抱歉!评论已关闭.