Iphone 如何在ImageView的顶部(在Xcode中以编程方式)自动调整图像的大小?

Iphone 如何在ImageView的顶部(在Xcode中以编程方式)自动调整图像的大小?,iphone,uiimageview,scaling,contentmode,Iphone,Uiimageview,Scaling,Contentmode,我有一个imageView(比如100x100),我想用一个(更小的)图像(比如50x10)填充它,我希望图像位于视图的顶部,而不是视图的中间 如果我使用 imageView.contentMode = UIViewContentModeScaleAspectFit; 它以100x20(如所期望的)缩放图像填充视图,但在视图中间。p> 像这样: +---------+ | | |i m a g e| <---my image (scaled) | | +-

我有一个imageView(比如100x100),我想用一个(更小的)图像(比如50x10)填充它,我希望图像位于视图的顶部,而不是视图的中间

如果我使用

imageView.contentMode = UIViewContentModeScaleAspectFit;

它以100x20(如所期望的)缩放图像填充视图,但在视图中间。p> 像这样:

+---------+
|         |
|i m a g e| <---my image (scaled)
|         |
+---------+ <---my UIImageView
+---------+
|i m a g e|
|         |
|         |
+---------+
我明白了:

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

这可能是最糟糕的解决方案,但它是有效的,您应该先设置图像视图的帧,然后调用此方法

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

可悲的是,这是一个远比它应该是更困难的问题。对于
ui视图
,您只能使用1种内容模式,因此您必须选择最有效的方式。我想让它保持在
UIViewContentModeScaleAspectFit
,然后根据您想要的位置重新调整图像的中心位置。是的,这(几乎)就是我最后的方式。(我不明白您为什么这样做(因为您使用的是UIGraphics),而不是根据两种宽度(imageView和image)的比例(“手动”)以UIImageView帧的大小和渲染时的原始图像的大小来修复新图像。)然后将该图像放置在imageView中,无需缩放,但两种方法都可以。)
-(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;
}