iphone - 如何从 uiimageview 获取具有缩放填充选项集的 uiimage

标签 iphone objective-c uiimageview uiimage

我用手机(640*480)制作了一张图片,并将其放入uiimageview(300*300)中,并设置了比例填充选项。 我需要将 uiimageview(300*300,裁剪,调整大小) 中显示的相同图像发送到服务器......

我怎样才能得到它?

最佳答案

有一种快速但肮脏的方法可以做到这一点,即将 UIImageView 层渲染到图形上下文。

UIGraphicsBeginImageContext(self.bounds.size);
[self.imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

您需要导入<QuartzCore/QuartzCore.h>为此。

另一种方法是自己计算 AspectFill。

 CGSize finalImageSize = CGSizeMake(300,300);
 CGImageRef sourceImageRef = yourImage.CGImage;

CGFloat horizontalRatio = finalImageSize.width / CGImageGetWidth(sourceImageRef);
CGFloat verticalRatio = finalImageSize.height / CGImageGetHeight(sourceImageRef);
CGFloat ratio = MAX(horizontalRatio, verticalRatio); //AspectFill
CGSize aspectFillSize = CGSizeMake(CGImageGetWidth(sourceImageRef) * ratio, CGImageGetHeight(sourceImageRef) * ratio);


CGContextRef context = CGBitmapContextCreate(NULL,
                                             finalImageSize.width,
                                             finalImageSize.height,
                                             CGImageGetBitsPerComponent(sourceImageRef),
                                             0,
                                             CGImageGetColorSpace(sourceImageRef),
                                             CGImageGetBitmapInfo(sourceImageRef));

//Draw our image centered vertically and horizontally in our context.
CGContextDrawImage(context, 
                   CGRectMake((finalImageSize.width-aspectFillSize.width)/2,
                              (finalImageSize.height-aspectFillSize.height)/2,
                              aspectFillSize.width,
                              aspectFillSize.height),
                   sourceImageRef);

//Start cleaning up..
CGImageRelease(sourceImageRef);

CGImageRef finalImageRef = CGBitmapContextCreateImage(context);
UIImage *finalImage = [UIImage imageWithCGImage:finalImageRef];

CGContextRelease(context);
CGImageRelease(finalImageRef);
return finalImage;

关于iphone - 如何从 uiimageview 获取具有缩放填充选项集的 uiimage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11291187/

相关文章:

android - 单击文本框时防止 iPhone 放大?

iphone - glScissor(0,0,0,0) 硬崩溃 Apple iOS 设备

objective-c - 如何让 NSTextView 随文本一起增长?

ios - Swift:在动画期间中途更改 UIImageView 图像

swift - 使用 DispatchQueue swift 3 下载图像时发现 Optional 为 nil

iphone - 不同页面大小的 ScrollView 中的分页

iphone - 更改墙上照片贴的图标

iphone - 如何使 UINavigationBar 不下推 View ?

iphone - UIButton 选定状态在 iOS 7 中不起作用

ios - 试图移动 UIImageView,移动整个屏幕 View