2013-02-01 128 views
21

我有這個UIImageView,我有它的最大高度和最大寬度的值。我想實現的是我想要拍攝的圖像(任何寬高比和任何分辨率),我希望它適合邊框,所以圖片不會超過他們,但它可以縮小它們,因爲它想要。 (圖中標記爲紅色):調整UIImage的大小並更改UIImageView的大小

enter image description here

眼下圖像正確貼合所需的大小,但我有2個憂慮: 1. UIImageView不是調整後的圖像的大小相等,從而留下紅色背景(我不希望那樣) 2.如果圖像比我的UIImageView的高度小,那麼它的大小不會變小,它保持相同的高度。

這裏是我的代碼,我知道它錯了:

UIImage *actualImage = [attachmentsArray lastObject]; 
UIImageView *attachmentImageNew = [[UIImageView alloc] initWithFrame:CGRectMake(5.5, 6.5, 245, 134)]; 
attachmentImageNew.image = actualImage; 
attachmentImageNew.backgroundColor = [UIColor redColor]; 
attachmentImageNew.contentMode = UIViewContentModeScaleAspectFit; 

那麼,如何動態改變大小不僅UIImageView.image的,但整個UIImageView的,從而使得它的尺寸完全可調的內容。任何幫助將不勝感激,謝謝!

回答

30

當你得到一個調整圖像Get width of a resized image after UIViewContentModeScaleAspectFit的寬度和高度,你可以調整你的ImageView:

imageView.frame = CGRectMake(0, 0, resizedWidth, resizedHeight); 
imageView.center = imageView.superview.center; 

,如果它工作我沒有檢查,但我覺得都應該是OK

+1

如果在超級視圖後我不添加'!'它給我的錯誤'可選類型的值UIView?'如果我使用'!',則不固定'未固定'。 :imageView.center = imageView.superview!.center; – Alex

+0

如果您使用自動佈局,該怎麼辦?你不應該設置「框架」嗎? –

1

如果您有圖片大小,爲什麼不將圖片視圖的frame.size設置爲這個尺寸?

編輯----

好了,看到你的評論,我建議這樣的:

UIImageView *imageView; 
//so let's say you're image view size is set to the maximum size you want 

CGFloat maxWidth = imageView.frame.size.width; 
CGFloat maxHeight = imageView.frame.size.height; 

CGFloat viewRatio = maxWidth/maxHeight; 
CGFloat imageRatio = image.size.height/image.size.width; 

if (imageRatio > viewRatio) { 
    CGFloat imageViewHeight = round(maxWidth * imageRatio); 
    imageView.frame = CGRectMake(0, ceil((self.bounds.size.height - imageViewHeight)/2.f), maxWidth, imageViewHeight); 
} 
else if (imageRatio < viewRatio) { 
    CGFloat imageViewWidth = roundf(maxHeight/imageRatio); 
    imageView.frame = CGRectMake(ceil((maxWidth - imageViewWidth)/2.f), 0, imageViewWidth, maxHeight); 
} else { 
    //your image view is already at the good size 
} 

此代碼將調整圖片大小,以便將其圖像比例,也是圖像視圖的位置與您的「默認」位置相同的中心。

PS:我希望你,如果你正在使用的CALayer陰影特效設置imageView.layer.shouldRasterise = YESimageView.layer.rasterizationScale = [UIScreen mainScreen].scale;

;)這將大大提高你的用戶界面的性能。

+0

你爲什麼認爲我用'attachmentImageNew.contentMode = UIViewContentModeScaleAspectFit'調整它的大小?因爲圖像太大。我無法將'imageView'的大小設置爲其圖像大小的準確值,因爲我的高度和寬度都是最大值。幾乎90%的圖像必須調整大小。 –

0

我想你想要的是不同的content mode。嘗試使用UIViewContentModeScaleToFill。這將根據需要通過改變內容的高寬比來縮放內容以適合UIImageView的大小。

看看官方文檔中的content mode部分,可以更好地瞭解可用的不同內容模式(圖片中有說明)。

+0

我想,它超越了我的'UIImageView'的限制進入星系很遠很遠 –

+0

這聽起來像星球大戰錯誤然後:-) – tiguero

+0

嗯,這是沒有任何錯誤,它只是表現得像是,我不認爲我需要'contentMode',我需要更強大的功能 –

22
- (UIImage *)image:(UIImage*)originalImage scaledToSize:(CGSize)size 
{ 
    //avoid redundant drawing 
    if (CGSizeEqualToSize(originalImage.size, size)) 
    { 
     return originalImage; 
    } 

    //create drawing context 
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f); 

    //draw 
    [originalImage drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)]; 

    //capture resultant image 
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    //return image 
    return image; 
} 
4

使用下面的類別,然後從石英申請邊境進入你的形象:

[yourimage.layer setBorderColor:[[UIColor whiteColor] CGColor]]; 
[yourimage.layer setBorderWidth:2]; 

類別: UIImage + AutoScaleResize。^ h

#import <Foundation/Foundation.h> 

@interface UIImage (AutoScaleResize) 

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize; 

@end 

的UIImage + AutoScaleResize.m

#import "UIImage+AutoScaleResize.h" 

@implementation UIImage (AutoScaleResize) 

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize 
{ 
    UIImage *sourceImage = self; 
    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; // scale to fit height 
     } 
     else 
     { 
      scaleFactor = heightFactor; // scale to fit width 
     } 

     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; 
      } 
     } 
    } 

    UIGraphicsBeginImageContext(targetSize); // this will crop 

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

    [sourceImage drawInRect:thumbnailRect]; 

    newImage = UIGraphicsGetImageFromCurrentImageContext(); 

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

    //pop the context to get back to the default 
    UIGraphicsEndImageContext(); 

    return newImage; 
} 

@end 
6

這是斯威夫特等效Rajneesh071的答案,使用擴展

UIImage { 
    func scaleToSize(aSize :CGSize) -> UIImage { 
    if (CGSizeEqualToSize(self.size, aSize)) { 
     return self 
    } 

    UIGraphicsBeginImageContextWithOptions(aSize, false, 0.0) 
    self.drawInRect(CGRectMake(0.0, 0.0, aSize.width, aSize.height)) 
    let image = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 
    return image 
    } 
} 

用法:

let image = UIImage(named: "Icon") 
item.icon = image?.scaleToSize(CGSize(width: 30.0, height: 30.0)) 
+0

這對我有用! – thejuki

0
if([[SDWebImageManager sharedManager] diskImageExistsForURL:[NSURL URLWithString:@"URL STRING1"]]) 
    { 
     NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:[NSURL URLWithString:@"URL STRING1"]]; 

     UIImage *tempImage=[self imageWithImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key] scaledToWidth:cell.imgview.bounds.size.width]; 
     cell.imgview.image=tempImage; 

    } 
    else 
    { 
     [cell.imgview sd_setImageWithURL:[NSURL URLWithString:@"URL STRING1"] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) 
     { 
      UIImage *tempImage=[self imageWithImage:image scaledToWidth:cell.imgview.bounds.size.width]; 
      cell.imgview.image=tempImage; 
//    [tableView beginUpdates]; 
//    [tableView endUpdates]; 

     }]; 
    } 
相關問題