iOS截取正方形的图片
博客专区 > 冰泪_ 的博客 > 博客详情
iOS截取正方形的图片
冰泪_ 发表于2年前
iOS截取正方形的图片
  • 发表于 2年前
  • 阅读 45
  • 收藏 0
  • 点赞 2
  • 评论 0

【腾讯云】如何购买服务器最划算?>>>   

摘要: iOS图片截取,

//截取正方形的图片 centerBool为YES  表示从中心开始截取
+(UIImage*)getSubImage:(UIImage *)image mCGRect:(CGRect)mCGRect centerBool:(BOOL)centerBool{
 /*如若centerBool为Yes则是由中心点取mCGRect范围的图片*/
 
 float imgWidth = image.size.width;
 float imgHeight = image.size.height;
 float viewWidth = mCGRect.size.width;
 float viewHidth = mCGRect.size.height;
 CGRect rect;
 if(centerBool)
     rect = CGRectMake((imgWidth-viewWidth)/2,(imgHeight-viewHidth)/2,viewWidth,viewHidth);
 else{
     if(viewHidth<viewWidth)
     {
         if(imgWidth<= imgHeight)
         {
             rect=CGRectMake(0, 0,imgWidth, imgWidth*viewHidth/viewWidth);
         }else
         {
             float width = viewWidth*imgHeight/viewHidth;
             float x = (imgWidth  - width)/2;
             if(x>0)
             {
                 rect = CGRectMake(x,0,  width, imgHeight);
             }else
             {
                 rect =  CGRectMake(0,  0,  imgWidth, imgWidth*viewHidth/viewWidth);
             }
         }
     }else
     {
         if(imgWidth <= imgHeight)
         {
             float height = viewHidth*imgWidth/viewWidth;
             if(height< imgHeight)
             {
                 rect =CGRectMake(0,  0, imgWidth, height);
             }else
             {
                 rect = CGRectMake(0,  0,viewWidth*imgHeight/viewHidth, imgHeight);
             }
         }else
         {
             float width = viewWidth*imgHeight/viewHidth;
             if(width< imgWidth)
             {
                 float x =  (imgWidth - width)/2;
                 rect =CGRectMake(x,  0,width, imgHeight);
             }else
             {
                 rect =CGRectMake(0,  0,imgWidth, imgHeight);
             }
         }
     }
 }
 
 CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage,rect);
 CGRect smallBounds =CGRectMake(0, 0,CGImageGetWidth(subImageRef),CGImageGetHeight(subImageRef));
 
 UIGraphicsBeginImageContext(smallBounds.size); CGContextRef context =UIGraphicsGetCurrentContext();CGContextDrawImage(context, smallBounds, subImageRef);
 UIImage *smallImage =[UIImage imageWithCGImage:subImageRef];
 UIGraphicsEndImageContext();
 
 return smallImage;
}

 

共有 人打赏支持
粉丝 13
博文 65
码字总数 45965
×
冰泪_
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: