gpt4 book ai didi

iphone - 如何以编程方式减少图像的内存大小

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:10:23 25 4
gpt4 key购买 nike

我正在开发一个应用程序。我正在从服务器获取图像。我想将这些图像用作 UIView 的背景。当我直接将这些图像用作 uiview 的背景时,UIView 加载速度非常慢。因此,在将该图像设置为 UIView 的背景之前,我想检查图像大小并减小图像的大小。所以请告诉我如何找出并更改图像的大小。我使用下面的代码将图像设置为 UIView

的背景
 UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"image.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.view.backgroundColor = [UIColor colorWithPatternImage:image];

drawrect 方法需要更多的时间来执行。

最佳答案

这是一个函数,您可以将其放入类别或辅助类中,以编程方式调整 UIImage 的大小。我在网站的某个地方找到了它,但我现在找不到确切的帖子。

请记住,这需要一些时间来处理。理想情况下,如果您希望在以后使用同一图像时获得性能提升,您应该只执行一次。

这里是:

+ (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize withOriginalImage:(UIImage *)origin {

UIImage *sourceImage = origin;
UIImage *newImage = nil;

CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;

CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;

CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;

CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

if (CGSizeEqualToSize(imageSize, targetSize) == NO) {

CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;

if (widthFactor < heightFactor)
scaleFactor = widthFactor;
else
scaleFactor = heightFactor;

scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;

// center the image

if (widthFactor < heightFactor) {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
} else if (widthFactor > heightFactor) {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}


// this is actually the interesting part:

UIGraphicsBeginImageContext(targetSize);

CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;

[sourceImage drawInRect:thumbnailRect];

newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

if(newImage == nil) NSLog(@"could not scale image");

return newImage ;
}

可以这样调用:

UIImage *mySmallImage = [ImageHelper imageByScalingProportionallyToSize:CGSizeMake(128,128) withOriginalImage:(UIImage *)myLargeImage];

关于iphone - 如何以编程方式减少图像的内存大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16233447/

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