How do I autoresize an image, but at the top of th

2019-08-11 19:43发布

I have an imageView (say 100x100) that I want to fill with a (smaller) image (say 50x10) and I want the image to go at the top of the view, not at the middle of the view.

If I use

imageView.contentMode = UIViewContentModeScaleAspectFit;

it fills the view with the image scaled at 100x20 (as expected) but in the middle of the view.

Like this:

+---------+
|         |
|i m a g e| <---my image (scaled)
|         |
+---------+ <---my UIImageView

If I set

imageView.contentMode = UIViewContentModeTop | UIViewContentModeScaleAspectFit;

I get this:

+---------+
|  image  | <---my image (not scaled)
|         |
|         |
+---------+

The image is not scaled and it stays at 50x10 in the middle of the imageView (as instructed by the UIViewContentModeTop, but it ignores UIViewContentModeScaleAspectFit).

How do I get it to accept both? Like this:

+---------+
|i m a g e|
|         |
|         |
+---------+

1条回答
我只想做你的唯一
2楼-- · 2019-08-11 20:08

This could be the worst solution but it works, You should set the frame of your image view first and then call this method.

-(void)adjustImageViewWithImageDimension:(CGRect)frame{
    UIImageView *tempView = [[UIImageView alloc] initWithFrame:frame];
    tempView.image = self.image;
    tempView.contentMode = UIViewContentModeScaleAspectFill;
    tempView.clipsToBounds = false;
    CGFloat oldAlpha = self.alpha;
    self.alpha = 1;
    UIGraphicsBeginImageContext(tempView.bounds.size);
    [tempView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.alpha = oldAlpha;
    self.image = resultingImage;
    self.contentMode = UIViewContentModeTop;
    self.clipsToBounds = YES;
}
查看更多
登录 后发表回答