简体   繁体   English

如何检测UIImageView的宽度和高度

[英]How to detect the width and height of a UIImageView

I'm looking to detect the width and height of an image and pass those dimensions into the following code: 我正在寻找检测图像的宽度和高度,并将这些尺寸传递给以下代码:

   UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(25, 5, imgView.size.width, imgView.size.width)];

Either there's something wrong with my syntax or this the wrong way to go about doing this. 我的语法有问题或执行此操作的错误方法。 Any help would be great, thanks 任何帮助都很好,谢谢

Do: 做:

UIImage *someImage = [UIImage imageNamed:@"someImage.png"];
UIImageView *someImageView = [[UIImageView alloc] initWithImage:someImage];
someImageView.frame = CGRectMake(0, 0, someImage.size.width, someImage.size.height);

Try this 尝试这个

UIImage *image = [UIImage imageNamed:@"image.png"];
UIImageView *imgView = [[UIImageView alloc] initWithImage:image];
imgView.frame = CGRectMake(0, 0, image.size.width, image.size.height);

Hope it helps you 希望对您有帮助

You can grab the size of an image from the UIImage size property. 您可以从UIImage size属性获取图像的size Maybe something like: 也许像:

UIImage *img = [UIImage imageNamed:@"image.png"];
UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(25, 5, img.size.width, img.size.width)];

Or you can just: 或者,您可以:

UIImageView *imgView=[[UIImageView alloc] initWithImage:img];

and it'll be sized automatically. 它将自动调整大小。

I suspect there is no width or height for the image view as you've just alloced and initialised it. 我怀疑图像视图没有宽度或高度,因为您刚刚对其进行了分配和初始化。 The initWithFrame initialisation methods requires a float value, so you can't query imgView to return a value for the width and height yet as its yet to be determined. initWithFrame初始化方法需要一个float值,因此您无法查询imgView返回宽度和高度的值(尚未确定)。

I usually would use the initialiser initWithImage. 我通常会使用初始化程序initWithImage。 Then modify the width and height of the imageview after initialisation. 然后在初始化后修改imageview的宽度和高度。

if you Want to set Maximum Width or Height then try this Code. 如果要设置最大宽度或最大高度,请尝试使用此代码。 it will control the size as well as you can set frame of image view dynamically. 它会控制尺寸以及您可以动态设置图像视图的框架。

CGSize size = image.size;

// Here Maximum width of image is 220 

    if (size.width > 220)
    {
        size.height /= (size.width / 220);
        size.width = 220;
    }
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
imageView.image = image;

// For layer mask or round corner

imageView.layer.cornerRadius = 5.0;
imageView.layer.masksToBounds = YES;

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

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