2013-02-01 87 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]; 

     }]; 
    } 
相关问题