How do I autoresize an image, but at the top of the ImageView (programmatically in Xcode)?

走远了吗. 提交于 2019-12-24 08:59:08

问题


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:


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


来源:https://stackoverflow.com/questions/13314018/how-do-i-autoresize-an-image-but-at-the-top-of-the-imageview-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!