UIImageView以错误的尺寸显示

时间:2015-12-28 10:04:10

标签: ios objective-c facebook uiimageview uiimage

我将UIImage加载到UIImageView并将图片的尺寸设置为与在故事板中创建的UIImageView相同,并且是60x60 by默认。代码方面,一切正常,调试说图像和imageView的尺寸都是60px,但是看模拟器,你可以看到一个矩形而不是一个盒子。问题在哪里?

图片加载代码:

- (void)viewWillAppear:(BOOL)animated
{   
    NSString *userImageURL = [NSString stringWithFormat:@"https://graph.facebook.com/TheOfficialKanyeWest/picture?"];
    NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:userImageURL]];
    UIImage* profilePic = [UIImage imageWithData:data];
    profilePic = [self imageWithImage:profilePic scaledToSize:profilePictureImageView.frame.size];
    [profilePictureImageView setImage:profilePic];
    //[profilePictureImageView sizeToFit];

    NSLog(@"\n\nView:\nWidth: %f\nHeight: %f\n\nImage:\nWidth: %f\nHeight: %f\n", profilePictureImageView.frame.size.width, profilePictureImageView.frame.size.height, profilePic.size.width, profilePic.size.height);
}

用于调整图像大小的自定义功能:

- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
    // Pass 1.0 to force exact pixel size.
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

另外,我在ViewDidAppear中输入的调试给了我:

View:
Width: 60.000000
Height: 60.000000

Image:
Width: 60.000000
Height: 60.000000

编辑: 忘了添加截图

screenshot

解决方案

代码绝对没问题。我没注意到我的自动约束导致imageView调整为奇怪的矩形形状。我手动添加了约束,现在效果很好。

4 个答案:

答案 0 :(得分:1)

在故事板中imageView到60和60的宽度高度约束不会使用自动约束。

答案 1 :(得分:1)

我已经尝试过你的代码,编码绝对正确,但在故事板中,自动布局有任何错误.. enter image description here

答案 2 :(得分:0)

将代码从viewWillAppear移至viewDidAppear。在viewWillAppear中,您的UIImageView未设置为最终帧。

答案 3 :(得分:0)

中试用您的代码
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// put your code to here to set frame and size of imageview.
}