问题描述
我有一个imageView(例如100x100),我想用一个(较小的)图像(例如50x10)填充,我希望该图像位于视图的顶部,而不是视图的中间.
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.
如果我使用
imageView.contentMode = UIViewContentModeScaleAspectFit;
它以比例为100x20(按预期)的图像填充视图,但位于视图的中间.
it fills the view with the image scaled at 100x20 (as expected) but in the middle of the view.
赞:
+---------+
| |
|i m a g e| <---my image (scaled)
| |
+---------+ <---my UIImageView
如果我设置
imageView.contentMode = UIViewContentModeTop | UIViewContentModeScaleAspectFit;
我明白了:
+---------+
| image | <---my image (not scaled)
| |
| |
+---------+
图像未未缩放,并且在imageView的中间停留在50x10(按照UIViewContentModeTop的指示,但是忽略了UIViewContentModeScaleAspectFit).
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;
}
这篇关于如何自动调整图像的大小,但是要在ImageView的顶部(以Xcode编程)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!