图像缩略图的坐标计算

rahulbsb

这是一个代码片段,用于创建缩略图大小的图像(根据原始的大图像)并将其适当地放置在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的原点)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章