iOS 中更改图像尺寸的几种方法
2017-08-27 本文已影响15人
能量达人儿
iOS 中有多种方法能够更改图片的尺寸,各种方法有不同的性能。
使用UIGraphicsBeginImageContext
UIKit
框架中提供了UIGraphicsBeginImageContext() 和 UIGraphicsGetImageFromCurrentImageContext()方法来更改图像尺寸。
+ (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)size {
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
使用CGBitmapContextCreate & CGContextDrawImage
Core Graphics / Quartz 2D 同样提供了 APIs 来处理图片尺寸调整。
+ (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)size {
CGImageRef cgImage = image.CGImage;
size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage);
size_t bytesPerRow = CGImageGetBytesPerRow(cgImage);
CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage);
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(cgImage);
CGContextRef context = CGBitmapContextCreate(nil, size.width, size.height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), cgImage);
UIImage *scaredImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];
CGContextRelease(context);
CGImageRelease(cgImage);
return scaledImage;
}