[英]How to detect the width and height of a UIImageView
我正在寻找检测图像的宽度和高度,并将这些尺寸传递给以下代码:
UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(25, 5, imgView.size.width, imgView.size.width)];
我的语法有问题或执行此操作的错误方法。 任何帮助都很好,谢谢
做:
UIImage *someImage = [UIImage imageNamed:@"someImage.png"];
UIImageView *someImageView = [[UIImageView alloc] initWithImage:someImage];
someImageView.frame = CGRectMake(0, 0, someImage.size.width, someImage.size.height);
尝试这个
UIImage *image = [UIImage imageNamed:@"image.png"];
UIImageView *imgView = [[UIImageView alloc] initWithImage:image];
imgView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
希望对您有帮助
您可以从UIImage
size
属性获取图像的size
。 也许像:
UIImage *img = [UIImage imageNamed:@"image.png"];
UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(25, 5, img.size.width, img.size.width)];
或者,您可以:
UIImageView *imgView=[[UIImageView alloc] initWithImage:img];
它将自动调整大小。
我怀疑图像视图没有宽度或高度,因为您刚刚对其进行了分配和初始化。 initWithFrame初始化方法需要一个float值,因此您无法查询imgView返回宽度和高度的值(尚未确定)。
我通常会使用初始化程序initWithImage。 然后在初始化后修改imageview的宽度和高度。
如果要设置最大宽度或最大高度,请尝试使用此代码。 它会控制尺寸以及您可以动态设置图像视图的框架。
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.