简体   繁体   English

如何设置UIImageView的特定大小

[英]How to set specific size to UIImageView

I got a weird bug going on. 我遇到了一个奇怪的错误。 I'm trying to programatically initialize an UIImageView with a specific frame and image. 我正在尝试以编程方式初始化具有特定框架和图像的UIImageView。 My image is 60x60, but I'm trying to resize it to 30x30 on the screen, which seems impossible. 我的图片是60x60,但我正在尝试在屏幕上将其尺寸调整为30x30,这似乎是不可能的。

The following works, but show the image in 60x60: 以下工作原理,但是以60x60的分辨率显示图像:

 UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo.png"]];
    [imgView setContentMode:UIViewContentModeScaleAspectFit];
//    imgView.frame = CGRectMake(100, 200, 30, 30);
    imgView.center = CGPointMake(pointTouch.x, pointTouch.y);
    [self.view addSubview:imgView];

And the following just doesn't show anything at all on the screen: 而且以下内容根本没有在屏幕上显示任何内容:

  UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo.png"]];
    [imgView setContentMode:UIViewContentModeScaleAspectFit];
    imgView.frame = CGRectMake(100, 200, 30, 30);
    imgView.center = CGPointMake(pointTouch.x, pointTouch.y);
    [self.view addSubview:imgView];

What's wrong? 怎么了?

EDIT : for those having the same problem, here is the working code: 编辑对于那些有相同的问题,这是工作代码:

UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo.png"]];
imgView.frame = CGRectMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2, 30, 30);
imgView.center = CGPointMake(pointTouch.x, pointTouch.y);
[imgView setContentMode:UIViewContentModeScaleAspectFill];
[self.view addSubview:imgView];

Start experiment with 开始实验

imgView.center = CGPointMake(view.bounds.x/2, view.bounds.y/2);
imgView.bounds = view.bounds; 

and see if this fills the superview. 看看这是否充满了超级视图。 Then try CGPointMake(pointTouch.x, pointTouch.y) and CGPointMake(30,30) respectively. 然后分别尝试CGPointMake(pointTouch.x, pointTouch.y)CGPointMake(30,30)

I'm guessing this behaviour has something to do with warning about frame : 我猜想这种行为与有关frame 警告有关

If the transform property is not the identity transform, the value of this property is undefined and therefore should be ignored. 如果transform属性不是恒等变换,则此属性的值未定义,因此应忽略。

You could try initializing the UIImageView with a set frame, then setting the image after that: 您可以尝试使用设置的框架初始化UIImageView ,然后在那之后设置图像:

UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 200, 30, 30)];
[imgView setContentMode:UIViewContentModeScaleAspectFit];
imgView.image = [UIImage imageNamed:@"logo.png"];
imgView.center = CGPointMake(pointTouch.x, pointTouch.y);
[self.view addSubview:imgView];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM