CGRect 图像大小调整
Posted
技术标签:
【中文标题】CGRect 图像大小调整【英文标题】:CGRect image resizing 【发布时间】:2010-09-02 23:32:56 【问题描述】:我正在使用 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]];
感谢您的帮助。
【问题讨论】:
【参考方案1】:拥有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];
【讨论】:
效果很好。谢谢,如果我想使矩形居中,你会用'0.0f,40.0f'点来做吗?还是有更好的方法,因为图像尺寸不同? 您可以将它们默认为 0,0,然后设置图像视图的中心属性:developer.apple.com/iphone/library/documentation/uikit/… 可能值得浏览一下 UIImage、UIImageView 和 UIView 的文档,因为那里可能还有其他有用的东西为你。阅读顶部的可用方法和属性列表将是一个好的开始,阅读这三个页面的介绍部分也是如此,只是为了了解 Apple 将什么放在哪里。【参考方案2】: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;
【讨论】:
感谢您的提示!由于我之前没有处理过修改 Objective-C 类,这些证明是有用的:Apple 和 Wikipedia以上是关于CGRect 图像大小调整的主要内容,如果未能解决你的问题,请参考以下文章