我想调整UIImage的大小,同时保持其纵横比.我已经写了下面的代码,但是没有按预期的方式工作.
码
-(UIImage * ) scaleImage: (UIImage * ) image toSize: (CGSize) targetSize { CGFloat scaleFactor = 1.0; if (image.size.width > targetSize.width || image.size.height > targetSize.height) if (!((scaleFactor = (targetSize.width / image.size.width)) > (targetSize.height / image.size.height))) //scale to fit width,or scaleFactor = targetSize.height / image.size.height; // scale to fit heigth. UIGraphicsBeginImageContext(targetSize); CGRect rect = CGRectMake((targetSize.width - image.size.width * scaleFactor) / 2,(targetSize.height - image.size.height * scaleFactor) / 2,image.size.width * scaleFactor,image.size.height * scaleFactor); [image drawInRect: rect]; UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; }
这里究竟是错的?
解决方法
我在几个项目中使用类似的东西:
- (UIImage*) scaleImage:(UIImage*)image toSize:(CGSize)newSize { CGSize scaledSize = newSize; float scaleFactor = 1.0; if( image.size.width > image.size.height ) { scaleFactor = image.size.width / image.size.height; scaledSize.width = newSize.width; scaledSize.height = newSize.height / scaleFactor; } else { scaleFactor = image.size.height / image.size.width; scaledSize.height = newSize.height; scaledSize.width = newSize.width / scaleFactor; } UIGraphicsBeginImageContextWithOptions( scaledSize,NO,0.0 ); CGRect scaledImageRect = CGRectMake( 0.0,0.0,scaledSize.width,scaledSize.height ); [image drawInRect:scaledImageRect]; UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; }