手机裁剪圆角图片_iOS高效图片圆角裁剪方法

自定义裁剪算法

- (UIImage *)dealImage:(UIImage *)img cornerRadius:(CGFloat)c {

// 1.CGDataProviderRef 把 CGImage 转 二进制流

CGDataProviderRef provider = CGImageGetDataProvider(img.CGImage);

void *imgData = (void *)CFDataGetBytePtr(CGDataProviderCopyData(provider));

int width = img.size.width * img.scale;

int height = img.size.height * img.scale;

// 2.处理 imgData

// dealImage(imgData, width, height);

cornerImage(imgData, width, height, c);

// 3.CGDataProviderRef 把 二进制流 转 CGImage

CGDataProviderRef pv = CGDataProviderCreateWithData(NULL, imgData, width * height * 4, releaseData);

CGImageRef content = CGImageCreate(width , height, 8, 32, 4 * width, CGColorSpaceCreateDeviceRGB(), kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast, pv, NULL, true, kCGRenderingIntentDefault);

UIImage *result = [UIImage imageWithCGImage:content];

CGDataProviderRelease(pv); // 释放空间

CGImageRelease(content);

return result;

}

其它方法

void releaseData(void *info, const void *data, size_t size) {

free((void *)data);

}

核心方法

// 裁剪圆角

void cornerImage(UInt32 *const img, int w, int h, CGFloat cornerRadius) {

CGFloat c = cornerRadius;

CGFloat min = w > h ? h : w;

if (c < 0) { c = 0; }

if (c > min * 0.5) { c = min * 0.5; }

// 左上 y:[0, c), x:[x, c-y)

for (int y=0; y

for (int x=0; x

UInt32 *p = img + y * w + x; // p 32位指针,RGBA排列,各8位

if (isCircle(c, c, c, x, y) == false) {

*p = 0;

}

}

}

// 右上 y:[0, c), x:[w-c+y, w)

int tmp = w-c;

for (int y=0; y

for (int x=tmp+y; x

UInt32 *p = img + y * w + x;

if (isCircle(w-c, c, c, x, y) == false) {

*p = 0;

}

}

}

// 左下 y:[h-c, h), x:[0, y-h+c)

tmp = h-c;

for (int y=h-c; y

for (int x=0; x

UInt32 *p = img + y * w + x;

if (isCircle(c, h-c, c, x, y) == false) {

*p = 0;

}

}

}

// 右下 y~[h-c, h), x~[w-c+h-y, w)

tmp = w-c+h;

for (int y=h-c; y

for (int x=tmp-y; x

UInt32 *p = img + y * w + x;

if (isCircle(w-c, h-c, c, x, y) == false) {

*p = 0;

}

}

}

}

判断点 (px, py) 在不在圆心 (cx, cy) 半径 r 的圆内

static inline bool isCircle(float cx, float cy, float r, float px, float py) {

if ((px-cx) * (px-cx) + (py-cy) * (py-cy) > r * r) {

return false;

}

return true;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值