[英]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.