我正在使用CGRect来显示图像。我希望CGRect在没有指定的情况下使用图像的宽度和高度。
可以这样:
CGRectMake(0.0f, 40.0f, 480.0f, 280.0f);
成为这个:
CGRectMake(0.0f, 40.0f, myImage.width, myImage.height);
当我指定参数时,某些图像会失真。
这是代码:
CGRect myImageRect = CGRectMake(0.0f, 40.0f, 480.0f, 280.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:recipe.img]];
感谢您的帮助。
答案 0 :(得分:8)
获得UIImage
后,您可以通过查看size属性找到其大小:
UIImage * image = [UIImage imageNamed:recipe.img];
CGRect rect = CGRectMake(0.0f, 40.0f, image.size.width, image.size.height);
UIImageView * imageView = [[UIImageView alloc] initWithFrame:rect];
[imageView setImage:image];
答案 1 :(得分:3)
UIImage上的这个类别可能会有所帮助。
像这样使用:aImage =[aImage imageByScalingProportionallyToSize: myImageRect]
@implementation UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {
UIImage *sourceImage = self;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor < heightFactor)
scaleFactor = widthFactor;
else
scaleFactor = heightFactor;
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
// if (widthFactor < heightFactor) {
// thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
// } else if (widthFactor > heightFactor) {
// thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
// }
//thumbnailPoint.x
}
// this is actually the interesting part:
UIGraphicsBeginImageContext(targetSize);
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if(newImage == nil) NSLog(@"could not scale image");
return newImage ;
}
@end;