美文网首页iOS开发知识小集
ios图片剪切2019版本

ios图片剪切2019版本

作者: iOS阿能 | 来源:发表于2019-04-02 00:18 被阅读18次

    也许打代码就是喜欢看到知识与成长的一部分吧

    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;
        }
    }
    

    相关文章

      网友评论

        本文标题:ios图片剪切2019版本

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