ios – 制作UIImage的正方形裁剪图像以拉伸图像

前端之家收集整理的这篇文章主要介绍了ios – 制作UIImage的正方形裁剪图像以拉伸图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当尝试执行UI Image的中心裁剪时,我得到以下结果(左边是640 * 1136处的原始图像,右边是适合320 * 320的正方形UIImageView的裁剪图像):

转向:

我对比率元素进行了相当多的修改,以便能够正确地检测要修剪的数量:使用图像的较短边,构建基于short_side / width_of_desired_rect的比率,但在这种情况下似乎不起作用.帮助赞赏!

- (UIImage *)squareImageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    double ratio;
    double delta;
    CGPoint offset;

    //make a new square size,that is the resized imaged width
    CGSize sz = CGSizeMake(newSize.width,newSize.width);

    //figure out if the picture is landscape or portrait,then
    //calculate scale factor and offset
    if (image.size.width > image.size.height) {
        ratio = newSize.width / image.size.width;
        delta = (ratio*image.size.width - ratio*image.size.height);
        offset = CGPointMake(delta/2,0);
    } else {
        ratio = newSize.width / image.size.height;
        delta = (ratio*image.size.height - ratio*image.size.width);
        offset = CGPointMake(0,delta/2);
    }

    //make the final clipping rect based on the calculated values
    CGRect clipRect = CGRectMake(-offset.x,-offset.y,(ratio * image.size.width) + delta,(ratio * image.size.height) + delta);

    //for retina consideration
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
        UIGraphicsBeginImageContextWithOptions(sz,YES,0.0);
    } else {
        UIGraphicsBeginImageContext(sz);
    }
    UIRectClip(clipRect);
    [image drawInRect:clipRect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

解决方法

试试这个:
- (UIImage *)squareImageFromImage:(UIImage *)image scaledToSize:(CGFloat)newSize {
    CGAffineTransform scaleTransform;
    CGPoint origin;

    if (image.size.width > image.size.height) {
        CGFloat scaleRatio = newSize / image.size.height;
        scaleTransform = CGAffineTransformMakeScale(scaleRatio,scaleRatio);

        origin = CGPointMake(-(image.size.width - image.size.height) / 2.0f,0);
    } else {
        CGFloat scaleRatio = newSize / image.size.width;
        scaleTransform = CGAffineTransformMakeScale(scaleRatio,scaleRatio);

        origin = CGPointMake(0,-(image.size.height - image.size.width) / 2.0f);
    }

    CGSize size = CGSizeMake(newSize,newSize);
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
        UIGraphicsBeginImageContextWithOptions(size,0);
    } else {
        UIGraphicsBeginImageContext(size);
    }

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextConcatCTM(context,scaleTransform);

    [image drawAtPoint:origin];

    image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}

猜你在找的iOS相关文章