1.图片模糊处理:
方法一:
+ (UIImage *)coreBlurImage:(UIImage *)image withBlurNumber:(CGFloat)blur { CIContext *context = [CIContext contextWithOptions:nil]; CIImage *inputImage=[CIImage imageWithCGImage:image.CGImage]; CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"]; [filter setValue:inputImage forKey:kCIInputImageKey]; [filter setValue:@(blur) forKey: @"inputRadius"]; //模糊图片 CIImage *result=[filter valueForKey:kCIOutputImageKey]; CGImageRef outImage=[context createCGImage:result fromRect:[result extent]]; UIImage *blurImage=[UIImage imageWithCGImage:outImage]; CGImageRelease(outImage); return blurImage; }
这是在网上所出来最多的一个方法,但是在使用的时候发现非常消耗性能,会阻塞主线程,效果很差。
方法二:
+ (UIImage *)boxblurImage:(UIImage *)image withBlurNumber:(CGFloat)blur { if (blur < 0.f || blur > 1.f) { blur = 0.5f; } int boxSize = (int)(blur * 40); boxSize = boxSize - (boxSize % 2) + 1; CGImageRef img = image.CGImage; vImage_Buffer inBuffer, outBuffer; vImage_Error error; void *pixelBuffer; //从CGImage中获取数据 CGDataProviderRef inProvider = CGImageGetDataProvider(img); CFDataRef inBitmapData = CGDataProviderCopyData(inProvider); //设置从CGImage获取对象的属性 inBuffer.width = CGImageGetWidth(img); inBuffer.height = CGImageGetHeight(img); inBuffer.rowBytes = CGImageGetBytesPerRow(img); inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData); pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img)); if(pixelBuffer == NULL) NSLog(@"No pixelbuffer"); outBuffer.data = pixelBuffer; outBuffer.width = CGImageGetWidth(img); outBuffer.height = CGImageGetHeight(img); outBuffer.rowBytes = CGImageGetBytesPerRow(img); error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend); if (error) { NSLog(@"error from convolution %ld", error); } CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef ctx = CGBitmapContextCreate( outBuffer.data, outBuffer.width, outBuffer.height, 8, outBuffer.rowBytes, colorSpace, kCGImageAlphaNoneSkipLast); CGImageRef imageRef = CGBitmapContextCreateImage (ctx); UIImage *returnImage = [UIImage imageWithCGImage:imageRef]; //释放C对象 CGContextRelease(ctx); CGColorSpaceRelease(colorSpace); free(pixelBuffer); CFRelease(inBitmapData); CGImageRelease(imageRef); return returnImage; }这个方法在性能上就好了很多,非常流程
2.自动获取图片尺寸
方法一:
-(void)test1{ UIImageView * imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Irelia_0.jpg"]]; [imageView sizeToFit]; NSLog(@"%@", NSStringFromCGRect(imageView.frame)); }这个方法主要是通过 sizeToFit 获取imageView的尺寸
方法二:
-(void)test2{ UIImageView * imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Irelia_0.jpg"]]; CGImageRef img = imageView.image.CGImage; CGFloat imageWidth = (CGFloat)CGImageGetWidth(img); CGFloat imageHeight = (CGFloat)CGImageGetHeight(img); NSLog(@"imageWidth:%f====imageHeight:%f", imageWidth, imageHeight); }这个方法主要是通过 CGImageGetWidth和CGImageGetHeight 来获取image的尺寸