Return a subimage from a UIImage

后端 未结 3 766
不知归路
不知归路 2020-12-08 11:45

I want to grab a subimage from a UIImage. I\'ve looked around for a similar question, to no avail.

I know the range of pixels I want to grab - how can I return th

相关标签:
3条回答
  • 2020-12-08 12:01

    Updated @donkim answer for swift 3:

        let fromRect=CGRect(x:0,y:0,width:320,height:480)
        let drawImage = image.cgImage!.cropping(to: fromRect)
        let bimage = UIImage(cgImage: drawImage!)
    
    0 讨论(0)
  • 2020-12-08 12:10

    In Swift 4, taking into account screen scale (otherwise your new image will be too large):

        let img = UIImage(named: "existingImage")!
        let scale = UIScreen.main.scale
        let dy: CGFloat = 6 * scale // say you want 6pt from bottom
        let area = CGRect(x: 0, y: img.size.height * scale - dy, width: img.size.width * scale, height: dy)
        let crop = img.cgImage!.cropping(to: area)!
        let subImage = UIImage(cgImage: crop, scale: scale, orientation:.up)
    
    0 讨论(0)
  • 2020-12-08 12:18

    This should help: http://iphonedevelopment.blogspot.com/2010/11/drawing-part-of-uiimage.html

    This code snippet is creating a category of UIImage but the code should be easily modified to work without it being a category.

    A shorter way of doing the same thing is the following:

    CGRect fromRect = CGRectMake(0, 0, 320, 480); // or whatever rectangle
    
    CGImageRef drawImage = CGImageCreateWithImageInRect(image.CGImage, fromRect);
    UIImage *newImage = [UIImage imageWithCGImage:drawImage];
    CGImageRelease(drawImage);
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题