ios图片剪切2019版本
2019-04-02 本文已影响18人
iOS阿能
也许打代码就是喜欢看到知识与成长的一部分吧
image.png+ (UIImage *)sourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize{
CGFloat souceImageW = sourceImage.size.width;
CGFloat souceImageH = sourceImage.size.height;
if (souceImageH == 0 || souceImageW == 0) {
return sourceImage;
}
BOOL isBiggerH = souceImageH > souceImageW;
CGFloat targetW = isBiggerH ? MIN(targetSize.width, targetSize.height) : MAX(targetSize.width, targetSize.height);
CGFloat targetH = isBiggerH ? MAX(targetSize.width, targetSize.height) : MIN(targetSize.width, targetSize.height);
CGFloat coefficientW = targetW * 1.0 / souceImageW;
CGFloat coefficientH = targetH * 1.0 / souceImageH ;
CGFloat finalCoefficient = MIN(coefficientW, coefficientH);
if (finalCoefficient > 1) {
return sourceImage; // 不需要缩小
}else{
CGPoint thumbnailPoint =CGPointMake(0.0,0.0);//这个是图片剪切的起点位置
UIGraphicsBeginImageContext(CGSizeMake(MIN(finalCoefficient * souceImageW, targetW), MIN(finalCoefficient * souceImageH, targetH)));//开始剪切
CGRect thumbnailRect =CGRectZero;//剪切起点(0,0)
thumbnailRect.origin= thumbnailPoint;
thumbnailRect.size.width= souceImageW * finalCoefficient;
thumbnailRect.size.height= souceImageH * finalCoefficient;
[sourceImage drawInRect:thumbnailRect];
UIImage*newImage =UIGraphicsGetImageFromCurrentImageContext();//截图拿到图片
return newImage;
}
}