The simplest way to resize an UIImage?

前端 未结 30 2640
迷失自我
迷失自我 2020-11-21 22:38

In my iPhone app, I take a picture with the camera, then I want to resize it to 290*390 pixels. I was using this method to resize the image :

UIImage *newI         


        
30条回答
  •  难免孤独
    2020-11-21 22:54

    Proper Swift 3.0 for iOS 10+ solution: Using ImageRenderer and closure syntax:

    func imageWith(newSize: CGSize) -> UIImage {
        let renderer = UIGraphicsImageRenderer(size: newSize)
        let image = renderer.image { _ in
            self.draw(in: CGRect.init(origin: CGPoint.zero, size: newSize))
        }
    
        return image.withRenderingMode(self.renderingMode)
    }
    

    And here's the Objective-C version:

    @implementation UIImage (ResizeCategory)
    - (UIImage *)imageWithSize:(CGSize)newSize
    {
        UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:newSize];
        UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext*_Nonnull myContext) {
            [self drawInRect:(CGRect) {.origin = CGPointZero, .size = newSize}];
        }];
        return [image imageWithRenderingMode:self.renderingMode];
    }
    @end
    

提交回复
热议问题