美文网首页
2019-09-25

2019-09-25

作者: 杯中怎可无酒 | 来源:发表于2019-09-25 14:20 被阅读0次
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize {
    CGSize imageSize = self.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; // scale to fit height
        }else {
            scaleFactor = heightFactor; // scale to fit width
        }
        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;
        }
    }
 
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [self drawInRect:thumbnailRect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
 
    if(newImage == nil) {
      NSLog(@"无法缩放图像");
    }  
    //弹出上下文以返回默认值
    UIGraphicsEndImageContext();
 
    return newImage;
}

相关文章

  • 2019-09-26

    ## 基金 & 理财 #### (2019-09-25 12:44:27) ### 金融名词 - **年化收益率*...

  • 10月2日

    2019-10-2 毛雅亭 字数 445 · 阅读 13 2019-09-25 08:27 ...

  • 9月27日

    2019-9-27 毛雅亭 字数 440 · 阅读 7 2019-09-25 08:27 ...

  • 9月28日

    2019-9-28 毛雅亭 字数 441 · 阅读 7 2019-09-25 08:27 ...

  • 9月25日

    2019-9-25 毛雅亭 字数 452 · 阅读 5 2019-09-25 08:27 ...

  • 9月24日

    2019-9-24 毛雅亭 字数 457 · 阅读 2 2019-09-25 08:27 ...

  • 10月27日

    2019-10-27 毛雅亭 字数 546 · 阅读 17 2019-09-25 08:27 ...

  • 10月26日

    2019-10-26 毛雅亭 字数 508 · 阅读 15 2019-09-25 08:27 ...

  • 10月30日

    2019-10-30 毛雅亭 字数 497 · 阅读 22 2019-09-25 08:27 ...

  • 11月2日

    2019-11-2 毛雅亭 字数 497 · 阅读 22 2019-09-25 08:27 ...

网友评论

      本文标题:2019-09-25

      本文链接:https://www.haomeiwen.com/subject/qsaiuctx.html