Proper use of UIRectClip to scale a UIImage down to icon size

前端 未结 3 496
清酒与你
清酒与你 2021-02-06 10:07

Given a UIImage of any dimension, I wish to generate a square \"icon\" sized version, px pixels to a side, without any distortion (stretching). How

3条回答
  •  孤独总比滥情好
    2021-02-06 10:18

    Eureka! I had things a little mixed up. This works:

    CGRect clipRect = CGRectMake(-offset.x, -offset.y,
                                 (ratio * size.width) + delta,
                                 (ratio * size.height) + delta);
    UIGraphicsBeginImageContext(CGSizeMake(px, px));
    UIRectClip(clipRect);
    [myImage drawInRect:clipRect];
    UIImage *icon = UIGraphicsGetImageFromCurrentImageContext();
    
    // Do something with the icon here ...
    
    UIGraphicsEndImageContext();
    

    No more need for rect. The trick appears to be using a negative offset in the clipping rectangle, thereby lining up the origin of where we want to grab our 50 x 50 image (in this example).

    Perhaps there's an easier way. If so, please weigh in!

提交回复
热议问题