图片涂抹马赛克逻辑步骤:
- 打开一张图片为前景图片
- 以前景图片生成一张虚化后的图片为背景图片
- 手指在屏幕涂抹,根据手指路径将背景图片绘制在前景图片上
- (UIImage *)transToMosaicImage:(UIImage*)orginImage blockLevel:(NSUInteger)level
{
//获取BitmapData
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGImageRef imgRef = orginImage.CGImage;
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);
CGContextRef context = CGBitmapContextCreate (nil,
width,
height,
kBitsPerComponent, //每个颜色值8bit
width*kPixelChannelCount, //每一行的像素点占用的字节数,每个像素点的ARGB四个通道各占8个bit
colorSpace,
kCGImageAlphaPremultipliedLast);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imgRef);
unsigned char *bitmapData = CGBitmapContextGetData (context);
//这里把BitmapData进行马赛克转换,就是用一个点的颜色填充一个level*level的正方形
unsigned char pixel[kPixelChannelCount] = {0};
NSUInteger index,preIndex;
for (NSUInteger i = 0; i < height - 1 ; i++) {
for (NSUInteger j = 0; j < width - 1; j++) {
index = i * width + j;
if (i % level == 0) {
if (j % level == 0) {
memcpy(pixel, bitmapData + kPixelChannelCount*index, kPixelChannelCount);
}else{
memcpy(bitmapData + kPixelChannelCount*index, pixel, kPixelChannelCount);
}
} else {
preIndex = (i-1)*width +j;
memcpy(bitmapData + kPixelChannelCount*index, bitmapData + kPixelChannelCount*preIndex, kPixelChannelCount);
}
}
}
NSInteger dataLength = width*height* kPixelChannelCount;
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, bitmapData, dataLength, NULL);
//创建要输出的图像
CGImageRef mosaicImageRef = CGImageCreate(width, height,
kBitsPerComponent,
kBitsPerPixel,
width*kPixelChannelCount ,
colorSpace,
kCGBitmapByteOrderDefault,
provider,
NULL, NO,
kCGRenderingIntentDefault);
CGContextRef outputContext = CGBitmapContextCreate(nil,
width,
height,
kBitsPerComponent,
width*kPixelChannelCount,
colorSpace,
kCGImageAlphaPremultipliedLast);
CGContextDrawImage(outputContext, CGRectMake(0.0f, 0.0f, width, height), mosaicImageRef);
CGImageRef resultImageRef = CGBitmapContextCreateImage(outputContext);
UIImage *resultImage = nil;
if([UIImage respondsToSelector:@selector(imageWithCGImage:scale:orientation:)]) {
// float scale = [[UIScreen mainScreen] scale];
resultImage = [UIImage imageWithCGImage:resultImageRef scale:orginImage.scale orientation:orginImage.imageOrientation];
} else {
resultImage = [UIImage imageWithCGImage:resultImageRef];
}
//释放
if(resultImageRef){
CFRelease(resultImageRef);
}
if(mosaicImageRef){
CFRelease(mosaicImageRef);
}
if(colorSpace){
CGColorSpaceRelease(colorSpace);
}
if(provider){
CGDataProviderRelease(provider);
}
if(context){
CGContextRelease(context);
}
if(outputContext){
CGContextRelease(outputContext);
}
return resultImage ;
}