如何按比例缩放UIImageView?

时间:2008-10-09 01:58:39

标签: objective-c cocoa-touch

我有一个UIImageView,目标是通过给它一个高度或宽度按比例缩小它。

UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 

//Add image view
[self.view addSubview:imageView];   

//set contentMode to scale aspect to fit
imageView.contentMode = UIViewContentModeScaleAspectFit;

//change width of frame
CGRect frame = imageView.frame;
frame.size.width = 100;
imageView.frame = frame;

图像确实已调整大小但位置不在左上角。缩放image / imageView的最佳方法是什么?如何更正位置?

17 个答案:

答案 0 :(得分:538)

一旦我找到了文档,很容易修复!

 imageView.contentMode = UIViewContentModeScaleAspectFit;

答案 1 :(得分:395)

我已经看过一些关于比例类型的讨论,所以我决定整理一个article regarding some of the most popular content mode scaling types

相关图片位于:

enter image description here

答案 2 :(得分:78)

我刚试过这个,而UIImage不支持_imageScaledToSize。

我最终使用类别向UIImage添加了一个方法 - 我在Apple Dev论坛上发现了一个建议。

在项目范围内.h -

@interface UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
@end;

实现:

@implementation UIImage (Extras)

- (UIImage *)imageByScalingProportionallyToSize:(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;
        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 ;
}

@end;

答案 3 :(得分:38)

imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;

答案 4 :(得分:30)

您可以尝试将imageView尺寸与image相匹配。以下代码未经过测试。

CGSize kMaxImageViewSize = {.width = 100, .height = 100};
CGSize imageSize = image.size;
CGFloat aspectRatio = imageSize.width / imageSize.height;
CGRect frame = imageView.frame;
if (kMaxImageViewSize.width / aspectRatio <= kMaxImageViewSize.height) 
{
    frame.size.width = kMaxImageViewSize.width;
    frame.size.height = frame.size.width / aspectRatio;
} 
else 
{
    frame.size.height = kMaxImageViewSize.height;
    frame.size.width = frame.size.height * aspectRatio;
}
imageView.frame = frame;

答案 5 :(得分:13)

UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 


//set contentMode to scale aspect to fit
imageView.contentMode = UIViewContentModeScaleAspectFit;

//change width of frame
//CGRect frame = imageView.frame;
//frame.size.width = 100;
//imageView.frame = frame;

//original lines that deal with frame commented out, yo.
imageView.frame = CGRectMake(10, 20, 60, 60);

...

//Add image view
[myView addSubview:imageView]; 

在iOS 4.2中发布的顶级原始代码对我来说效果很好。

我发现创建一个CGRect并指定所有top,left,width和height值是在我的情况下调整位置的最简单方法,即在表格单元格中使用UIImageView。 (仍然需要添加代码来释放对象)

答案 6 :(得分:12)

可以通过这种方式调整UIImage的大小

image = [UIImage imageWithCGImage:[image CGImage] scale:2.0 orientation:UIImageOrientationUp];

答案 7 :(得分:12)

选择模式为Aspect Fill设置您的ImageView,然后选中Clip Subviews框。

enter image description here

答案 8 :(得分:8)

对我来说这很好用Swift 2.x:

imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true;

答案 9 :(得分:6)

对于Swift:

#Check if there is a value
if '1/15' in data['Peter']:
  print 'Peter had any value of %s in week 1/15' % (data['Peter']['1/15'])
#Loop over the values
for person in data:
  for week, any_value in data[person].iteritems():
     print 'Person: %s ; Week: %s; Any Value: %s' % (person, week, value)

答案 10 :(得分:6)

按比例设置UIimageview .........

enter image description here

答案 11 :(得分:5)

的UIImageView + Scale.h:

#import <Foundation/Foundation.h>

@interface UIImageView (Scale)

-(void) scaleAspectFit:(CGFloat) scaleFactor;

@end

的UIImageView + Scale.m:

#import "UIImageView+Scale.h"

@implementation UIImageView (Scale)


-(void) scaleAspectFit:(CGFloat) scaleFactor{

    self.contentScaleFactor = scaleFactor;
    self.transform = CGAffineTransformMakeScale(scaleFactor, scaleFactor);

    CGRect newRect = self.frame;
    newRect.origin.x = 0;
    newRect.origin.y = 0;
    self.frame = newRect;
}

@end

答案 12 :(得分:2)

我使用了以下代码。其中imageCoverView是UIView保存UIImageView

if (image.size.height<self.imageCoverView.bounds.size.height && image.size.width<self.imageCoverView.bounds.size.width)
{
    [self.profileImageView sizeToFit];
    self.profileImageView.contentMode =UIViewContentModeCenter
}
else
{
    self.profileImageView.contentMode =UIViewContentModeScaleAspectFit;
}

答案 13 :(得分:2)

如果此处提出的解决方案不适合您,并且您的图像资源实际上是PDF,请注意XCode实际上对PDF的处理方式与图像文件不同。特别是,它似乎无法扩展以正确填充PDF:它最终会平铺。这让我疯狂,直到我发现问题是PDF格式。转换为JPG,你应该好好去。

答案 14 :(得分:1)

通常我会将此方法用于我的应用( Swift 2.x 兼容):

// Resize UIImage
func resizeImage(image:UIImage, scaleX:CGFloat,scaleY:CGFloat) ->UIImage {
    let size = CGSizeApplyAffineTransform(image.size, CGAffineTransformMakeScale(scaleX, scaleY))
    let hasAlpha = true
    let scale: CGFloat = 0.0 // Automatically use scale factor of main screen

    UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
    image.drawInRect(CGRect(origin: CGPointZero, size: size))

    let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return scaledImage
}

答案 15 :(得分:0)

我认为你可以做点什么

image.center = [[imageView window] center];

答案 16 :(得分:-3)

以下是如何轻松扩展它的方法。

这适用于模拟器和iPhone的2.x.

UIImage *thumbnail = [originalImage _imageScaledToSize:CGSizeMake(40.0, 40.0) interpolationQuality:1];