调整图像大小以适合UIImageView

时间:2012-09-23 13:36:38

标签: ios objective-c uiimageview uiimage

我对目标c非常新,我只是在考虑我的方向。我想做一些非常简单的事情,但事实证明这是一个很大的挑战:

我正在尝试将图片显示为UIImageView。我显示的图片很大,我希望它缩小以适应UIImageView。我尝试设置AspectFit查看模式,但图像显示为原始大小,并被UIImageView剪切。我的代码如下:

- (void)changeImages
{
    UIImage* img11 = nil;

    img11 = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"dog" ofType:@"jpeg"]];

    u11.contentMode = UIViewContentModeScaleAspectFit;
    u11.image = img11;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self changeImages];
}

有人可以对此有所了解吗?

谢谢!

6 个答案:

答案 0 :(得分:31)

嗨,我会试试这个......

- (void)changeImages
{
    UIImage *img11 = [UIImage imageNamed@"dog.jpeg"];

    u11.contentMode = UIViewContentModeScaleAspectFit;
    u11.clipsToBounds = YES;
    [u11 setImage:img11];
}

- (void)viewWillAppear:animated
{
    [super viewWillAppear:animated];

    [self changeImages];
}

这将缩放图像(向上或向下),使其适合imageView。拥有clipsToBounds不是必需的,但会阻止图像显示在imageView框架之外。

HTH。

答案 1 :(得分:17)

添加到您的UIViewController.m:

-(UIImage *)resizeImage:(UIImage *)image imageSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0,0,size.width,size.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // here is the scaled image which has been changed to the size specified
    UIGraphicsEndImageContext();
    return newImage;
}

使用:

UIImage *image = [UIImage imageNamed:@"image.png"];
CGSize size = CGSizeMake(50, 63); // set the width and height 
UIImage *resizedImage = [self resizeImage:image imageSize:size];

我希望它有所帮助。

答案 2 :(得分:4)

CGSize size=CGSizeMake(79, 84);//set the width and height
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0,0,size.width,size.height)];
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
//here is the scaled image which has been changed to the size specified
UIGraphicsEndImageContext();

这肯定是有效的,不要忘记导入QuartzCore FrameWork ..

快乐编码(^ _ ^)....

答案 3 :(得分:1)

您还可以在Interface Builder的“属性”检查器中将“视图:模式”设置为“适合宽高比”

答案 4 :(得分:0)

我做了以下操作并且有所帮助 将模式更改为"方面填充"从默认值"缩放到填充"

并添加一行代码,如下所示(我是在单元格配置中完成的):

cell.photo.clipsToBounds = true

答案 5 :(得分:0)

我知道这很古老,但是我想根据Stanford 193p 2017讲座11(约18:45)和所有快速查找的人添加一个回复,因为这是第一个显示给我的搜索结果。

基本上,子类化UIView并使其看起来像:

class U11: UIView {
    var myImage: UIImage? { didSet { setNeedsDisplay() }}
    override func draw(_ rect: CGRect) {
        myImage?.draw(in: bounds)
    }
}

然后将图像设置为:

func changeImage() {
    if let img11 = UIImage(named: "dog.jpeg"){
            u11.myImage = img11
    }
}

这非常简单,图像占据了视图边界内的整个空间。