我在许多文章中看到通过保持纵横比来调整图像大小.这些函数在调整大小时使用RECT的固定点(宽度和高度).但是在我的项目中,我需要仅根据宽度调整视图大小,应根据宽高比自动获取高度.有人帮助我实现这一目标.
可能重复:
使用宽高比调整UIImage的大小?
下面这段代码正在完美地调整图像大小,但问题是它会混淆纵横比(导致图像偏斜).有什么指针吗?
// Change image resolution (auto-resize to fit)
+ (UIImage *)scaleImage:(UIImage*)image toResolution:(int)resolution {
CGImageRef imgRef = [image CGImage];
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);
CGRect bounds = CGRectMake(0, 0, width, height);
//if already at the minimum resolution, return the orginal image, otherwise scale
if (width <= resolution && height <= resolution) {
return image;
} else {
CGFloat ratio = width/height;
if (ratio > 1) {
bounds.size.width = resolution;
bounds.size.height = bounds.size.width / ratio;
} else …Run Code Online (Sandbox Code Playgroud) UIView提供"方面适合"内容模式.但是,我是UIView的子类,并希望使用具有宽高比的drawInRect绘制UIImage.有没有办法让我在不使用UIImageView的情况下访问该功能?
我正在使用UIImagePickerController为我的应用程序选择图像.然而,我在维持所选图像的纵横比方面面临一些挑战
例如,
我手机上的原始图像如下(非方形图像):

通过"移动和缩放"页面在iphone上选择图像以裁剪图像后,结果如下:(此处仍保持宽高比)

我的应用程序将在带有方框(200 x 200)的UIImageView中显示所选图像.将所选图像设置为UIImageView(UIImageView.image = selectedImage)后,图像的宽高比不会保持,而是跟随UIImageView的框架:(图像看起来在我的UIImageView中现在倾斜):

在这种情况下,有没有办法保持图像的纵横比?
编辑:更新预期结果
经过一番思考,我意识到解决我的问题的最好方法是确保对于这样的图像(非正方形),我需要将它们"转换"成方形图像,即填充图像顶部和底部的空白区域以制作广场例如
预期图片:(添加了顶部和底部边框)

编辑:使用示例代码更新
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo
{
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
self.imageView.image = image;
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
//Compress image
UIImage *image = [self scaleImage:img toSize:CGSizeMake(612.0,612.0)];
self.imageData = UIImageJPEGRepresentation(image, 0.75);
}
Run Code Online (Sandbox Code Playgroud)
通过添加代码"self.imageView.contentMode = UIViewContentModeScaleAspectFill;",我能够在uiimageview中获取方形图像

但似乎原始图像仍然不是方形图像,因此当我执行"UIImage*image = [self scaleImage:img toSize:CGSizeMake(612.0,612.0)];"时,仍会出现偏斜问题.我的假设是否正确?无论如何要缓解这个问题,因为我仍然需要在应用程序的其他地方显示"压缩"图像.
我有应用程序可以添加相机或画廊的照片.添加每张照片后显示UIImageView.但他们表现出不好的宽高比.照片的UIImageView's尺寸有所扩大.
如何以真实的宽高比显示照片?
UPD和小图片怎么样?如果用户将添加非常小的图片,这张图片将在所有区域调整大小UIImageView.如何以实际尺寸显示这些图片?
我以编程方式设置带边框的imageview.我将imageView的内容模式设置为Aspect Fit,它可以工作,但边框仍然是原始方块.
码:
CGRect imageViewRect = CGRectMake(left, top, 158, 119);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:imageViewRect];
[imageView setContentMode:UIViewContentModeScaleAspectFit];
[imageView setImage:image];
[imageView.layer setBorderColor:[[UIColor blackColor] CGColor]];
[imageView.layer setBorderWidth:3.0];
Run Code Online (Sandbox Code Playgroud)
显然,我希望黑色边框可以根据纵横比调整,并在所有面上环绕图像.相反它保留在原始框架中,看起来像这样:

有什么区别CGImageGetWidth(workingImage.CGImage)和workingImage.size.width?第一个更快还是更安全?我知道在第二种情况下,我直接获得了值.
ios ×6
objective-c ×5
uiimage ×4
aspect-ratio ×3
iphone ×2
fixed-width ×1
resize ×1
uiimageview ×1