[英]IOS: problem with resize a UIImage
我想調整UIImage的大小,然后嘗試以下代碼:
UIImage *newImage = [image1toResize _imageScaledToSize:CGSizeMake(290, 390) interpolationQuality:1];
但是我有這個警告:警告:“ UIImage”可能不會響應“ -_imageScaledToSize:”
為什么?
您並沒有要求它,只是以防萬一您對如何操作感興趣...這是一個非常簡單的代碼:
CGSize newSize = CGSizeMake(1024, 768); //whaterver size
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
您可以通過以下方式調整大小:
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
//UIGraphicsBeginImageContext(newSize);
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
_imageScaledToSize不是UIImage函數。 如果此函數是正在使用的3rd Party庫的一部分,則需要確保#import正確的頭文件。
縮放圖像而不損失縱橫比(即不拉伸圖像)的最佳方法是使用以下方法:
//to scale images without changing aspect ratio
+(UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize {
float width = newSize.width;
float height = newSize.height;
UIGraphicsBeginImageContext(newSize);
CGRect rect = CGRectMake(0, 0, width, height);
float widthRatio = image.size.width / width;
float heightRatio = image.size.height / height;
float divisor = widthRatio > heightRatio ? widthRatio : heightRatio;
width = image.size.width / divisor;
height = image.size.height / divisor;
rect.size.width = width;
rect.size.height = height;
//indent in case of width or height difference
float offset = (width - height) / 2;
if (offset > 0) {
rect.origin.y = offset;
}
else {
rect.origin.x = -offset;
}
[image drawInRect: rect];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return smallImage;
}
將此方法添加到Utility類中,以便您可以在整個項目中使用它,並按如下方式訪問它:
xyzImageView.image = [Utility scaleImage:yourUIImage toSize:xyzImageView.frame.size];
此方法在保持縱橫比的同時要注意縮放。 萬一按比例縮小的圖像的寬度大於高度(或反之亦然),還會在圖像上添加縮進。
這是因為UIImage
類沒有這種方法。 您可以在此處找到可用的UIImage
方法的列表
您可以在UIImage
上使用以下類別來操縱UIImage
對象(例如,調整其大小或裁剪它們):
http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.