简体   繁体   中英

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. 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.

I usually would use the initialiser initWithImage. Then modify the width and height of the imageview after initialisation.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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