質問

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|
|         |
|         |
+---------+
役に立ちましたか?

解決

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;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top