gpt4 book ai didi

iphone - UIImage调整大小(缩放比例)

转载 作者:行者123 更新时间:2023-12-03 18:11:23 25 4
gpt4 key购买 nike

Possible Duplicate:
Resize UIImage with aspect ratio?

下面的代码完美地调整了图像的大小,但问题是它弄乱了纵横比(导致图像倾斜)。有什么指点吗?

// 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 {
bounds.size.height = resolution;
bounds.size.width = bounds.size.height * ratio;
}
}

UIGraphicsBeginImageContext(bounds.size);
[image drawInRect:CGRectMake(0.0, 0.0, bounds.size.width, bounds.size.height)];
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return imageCopy;
}

最佳答案

我使用这一行代码创建了一个已缩放的新 UIImage。设置比例和方向参数以实现您想要的效果。第一行代码只是抓取图像。

    // grab the original image
UIImage *originalImage = [UIImage imageNamed:@"myImage.png"];
// scaling set to 2.0 makes the image 1/2 the size.
UIImage *scaledImage =
[UIImage imageWithCGImage:[originalImage CGImage]
scale:(originalImage.scale * 2.0)
orientation:(originalImage.imageOrientation)];

关于iphone - UIImage调整大小(缩放比例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2645768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com