我将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
编辑: 忘了添加截图
解决方案
代码绝对没问题。我没注意到我的自动约束导致imageView调整为奇怪的矩形形状。我手动添加了约束,现在效果很好。
答案 0 :(得分:1)
在故事板中imageView
到60和60的宽度和高度约束不会使用自动约束。
答案 1 :(得分:1)
答案 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.
}