iOS url图片居中工具类

自己写的一个网络请求图片居中工具类

+(void)cropToolWithUrl:(NSString *)url imageView:(UIImageView *)imageView{
    [imageView sd_setImageWithURL:[NSURL URLWithString:url] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        CGFloat width = image.size.width;
        CGFloat height = image.size.height;
        if (width==height) {
            
        }else{
            CGSize  contextSize;
            CGFloat context_x_ctm;
            if(width>height){
                contextSize=CGSizeMake(height, height);
                context_x_ctm=-(width-height)/2;
                
            }else{
                contextSize=CGSizeMake(width, width);
                context_x_ctm=-(height-width)/2;
            }
            
            UIImage *croppedImage = nil;
            UIGraphicsBeginImageContextWithOptions(contextSize, true,1.0);
            {
                CGContextRef context = UIGraphicsGetCurrentContext();
                
                CGContextTranslateCTM(context, context_x_ctm, 0);
                [image drawAtPoint:CGPointZero];
                
                croppedImage = UIGraphicsGetImageFromCurrentImageContext();
            }
            UIGraphicsEndImageContext();
            
            UIImage *newImg =  [UIImage imageWithCGImage:croppedImage.CGImage scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
            imageView.image=newImg;
        }
    }];
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 紫鹊界梯田 梯田是人类在这个星球上顽强生存的创举,区别于北方平原沃土的广袤平坦,这里的沟沟壑壑,注定要造就一批穷究...
    左顾韶烬阅读 259评论 0 0
  • 最近做梦总梦到一个脏兮兮无法下脚的厕所,梦醒之后左思右想才发现原来那个厕所竟是初中时期的厕所,那个脏至今无法忘怀。...
    悠漾阅读 572评论 0 2
  • 笛卡尔曾经说过:“读一本好书,就是和许多高尚的人谈话。”是的,读一本好书,你能提高自己的写作水平和幻想能力,也可以...
    我们结束了阅读 257评论 0 1
  • 你听着安河桥说着平淡日子的刺 你想知道董小姐的秘密 宋胖子的斑马已经走远 民谣始终是你生活的态度 开心时你上扬的嘴...
    独家空白阅读 427评论 6 7