我想从UIImage中获取一个子图像。我四处寻找类似的问题,但无济于事。
我知道我想要抓取的像素范围 - 如何从现有图像中返回此子图像?
答案 0 :(得分:26)
这应该有所帮助:http://iphonedevelopment.blogspot.com/2010/11/drawing-part-of-uiimage.html
此代码段正在创建UIImage
类别,但代码应该很容易修改,以便在不属于某个类别的情况下工作。
执行相同操作的更简单方法如下:
CGRect fromRect = CGRectMake(0, 0, 320, 480); // or whatever rectangle
CGImageRef drawImage = CGImageCreateWithImageInRect(image.CGImage, fromRect);
UIImage *newImage = [UIImage imageWithCGImage:drawImage];
CGImageRelease(drawImage);
希望这有帮助!
答案 1 :(得分:4)
更新了swift 3的@donkim答案:
let fromRect=CGRect(x:0,y:0,width:320,height:480)
let drawImage = image.cgImage!.cropping(to: fromRect)
let bimage = UIImage(cgImage: drawImage!)
答案 2 :(得分:1)
在Swift 4中,请考虑屏幕比例(否则您的新图像将太大):
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)