您的位置:首页 > 移动开发 > IOS开发

【ios】把图片切成圆角代码 实现及问题

2012-09-28 17:25 246 查看
方法一(原生支持,简单明了,最大的问题是在tableview里面会拖慢速度,感觉会卡):

   self.imageView.layer.cornerRadius = 4;
   self.imageView.layer.masksToBounds = YES;

方法二:

@implementation ImageUtils

//把图片切成圆角代码
static void addRoundedRectToPath(CGContextRef context,CGRect rect,
float ovalWidth,
                                 float ovalHeight,float radius)
{
    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); // Start at lower right corner
    CGContextAddArcToPoint(context, fw, fh, fw/2, fh, radius); // Top right corner
    CGContextAddArcToPoint(context,
0, fh, 0, fh/2, radius);
// Top left corner
    CGContextAddArcToPoint(context,
0, 0, fw/2,
0, radius); // Lower left corner
    CGContextAddArcToPoint(context, fw,
0, fw, fh/2, radius); // Back to lower right
    
    CGContextClosePath(context);
    CGContextRestoreGState(context);
}

+ (id) createRoundedRectImage:(UIImage*)image size:(CGSize)size radius:(float) radius
{
    // the size of CGContextRef
    int w = size.width*2;  //解决图像模糊问题
    int h = size.height*2; //解决图像模糊问题
    
    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 ,radius);
    CGContextClosePath(context);
    CGContextClip(context);
    CGContextDrawImage(context,
CGRectMake(0, 0, w, h), image.CGImage);
    CGImageRef imageMasked =
CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return [UIImageimageWithCGImage:imageMasked];
}

@end

参考文章:
http://www.cocoachina.com/bbs/read.php?tid=1757&page=1 http://www.cocoachina.com/bbs/read.php?tid=73051&page=2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios float image null