How to show in UIImage just a part of image?

后端 未结 3 1129
旧巷少年郎
旧巷少年郎 2021-02-15 16:48

I have UIImageView in which I\'m showing 50x100 image.

I want to show only a part of image 50x50 (top part)?

How can I do that?

3条回答
  •  别跟我提以往
    2021-02-15 17:09

    You can crop the image by using CGImageCreateWithImageInRect, which is Quartz primitive working on CGImageRef, so you would have something like:

    CGImageRef imageRef = CGImageCreateWithImageInRect(originalImage.CGImage, cropRect);
    UIImage* outImage = [UIImage imageWithCGImage:imageRef scale:originalImage.scale orientation:originalImage.imageOrientation]]; 
    CGImageRelease(imageRef);
    

    When calculation cropRect, keep in mind that it should be given in pixels, not in points, i.e.:

    float scale = originalImage.scale;
    CGRect cropRect = CGRectMake(0, 0,
                             originalImage.size.width * scale, originalImage.size.height * 0.5 * scale);
    

    where the 0.5 factor accounts for the fact that you want the top half only.

    If you do not want to go low-level, you could add your image to a UIView as a background color and use the clipToBounds CALayer property to make the clipping:

    myView.backgroundColor = [UIColor colorWithBackgroundPattern:myImage];
    myView.layer.clipToBounds = YES;
    

    also, set myView bounds accordingly.

提交回复
热议问题