gpt4 book ai didi

iPhone 开发 : any snippet to resize an image and keep the ratio?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:19:35 24 4
gpt4 key购买 nike

我不熟悉在 iPhone 中开发代码,我想搜索一些代码以将我的 UIImage 调整为指定大小但保持比例。指定的大小类似于图像不能越过边界的框架,在该边界内图像应缩放以适合框架并保持比例,我当前使用的代码可以调整大小但不能保持ratio,只需将其粘贴到此处,看看我是否可以做一些微不足道的修改,使其成为可能。

- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize {
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
CGImageRef imageRef = image.CGImage;

UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();

// Set the quality level to use when rescaling
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);

CGContextConcatCTM(context, flipVertical);
// Draw into the context; this scales the image
CGContextDrawImage(context, newRect, imageRef);

// Get the resized image from the context and a UIImage
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];

CGImageRelease(newImageRef);
UIGraphicsEndImageContext();

return newImage;

最佳答案

好吧,您可以更简单地调整图像大小:

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

然后你需要计算一个新的尺寸来保持纵横比。例如要获得一半尺寸的图像,您将提供这样创建的尺寸:

  CGSize halfSize = CGSizeMake(image.size.width*0.5, image.size.height*0.5);

关于iPhone 开发 : any snippet to resize an image and keep the ratio?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11160464/

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