这是一个代码片段,用于创建缩略图大小的图像(从原始大图像)并将其适本地放置在 tableviewcell 的顶部。当我研究代码时,我陷入了通过设置横坐标和纵坐标来给缩略图指定位置的部分。在方法 -(void)setThumbDataFromImage:(UIImage *)image 中,他们设置项目缩略图的尺寸和坐标 -
-(void)setThumbnailDataFromImage:(UIImage *)image{
CGSize origImageSize= [image size];
// the rectange of the thumbnail
CGRect newRect= CGRectMake(0, 0, 40, 40);
// figure out a scaling ratio to make sure we maintain the same aspect ratio
float ratio= MAX(newRect.size.width/origImageSize.width, newRect.size.height/origImageSize.height);
// Create a transparent bitmap context with a scaling factor equal to that of the screen
UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 0.0);
// create a path that is a rounded rectangle
UIBezierPath *path= [UIBezierPath bezierPathWithRoundedRect:newRect cornerRadius:5.0];
// make all the subsequent drawing to clip to this rounded rectangle
[path addClip];
// center the image in the thumbnail rectangle
CGRect projectRect;
projectRect.size.width=ratio * origImageSize.width;
projectRect.size.height= ratio * origImageSize.height;
projectRect.origin.x= (newRect.size.width- projectRect.size.width)/2;
projectRect.origin.y= (newRect.size.height- projectRect.size.height)/2;
// draw the image on it
[image drawInRect:projectRect];
// get the image from the image context, keep it as our thumbnail
UIImage *smallImage= UIGraphicsGetImageFromCurrentImageContext();
[self setThumbnail:smallImage];
// get the PNG representation of the image and set it as our archivable data
NSData *data= UIImagePNGRepresentation(smallImage);
[self setThumbnailData:data];
// Cleanup image context resources, we're done
UIGraphicsEndImageContext();
}
我得到了宽度和高度的计算,其中我们将 origImageSize 乘以缩放因子/比率。 但是然后我们使用以下内容来给缩略图指定一个位置 -
projectRect.origin.x= (newRect.size.width- projectRect.size.width)/2;
projectRect.origin.y= (newRect.size.height- projectRect.size.height)/2;
这个我不明白。我无法理解它。 :? 这是居中过程的一部分。我的意思是,我们是否在这里使用数学关系来定位缩略图,或者它是一些随机计算,即可能是任何东西..我是否缺少这两行代码背后的一些基本原理?
最佳答案
这两行是用于将某些内容居中的标准代码,尽管它们并不是以最通用的方式编写的。您通常想要使用:
projectRect.origin.x = newRect.origin.x + newRect.size.width / 2.0 - projectRect.size.width / 2.0;
projectRect.origin.y = newRect.origin.y + newRect.size.height / 2.0 - projectRect.size.height / 2.0;
在您的例子中,作者知道原点是 0,0,因此他们省略了每行中的第一项。
由于要将一个矩形置于另一个矩形的中心,您希望两个轴的中心对齐,因此您可以取容器宽度的一半(外部矩形的中心)并减去内部矩形宽度的一半(这需要到内部矩形的左侧),这会给出内部矩形正确居中时左侧应该在的位置(例如:它的 x 原点)。
关于objective-c - 图像缩略图的坐标计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21349963/