从UIImage返回一个子图像

15

我想从UIImage中获取一个子图像。我查看了类似的问题,但没有找到合适的答案。

我知道要获取的像素范围 - 如何从现有的图像返回此子图像?

3个回答

28
这应该会有所帮助: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);

希望这可以帮到你!


这种方式应该在主线程下运行,它不是一个线程安全的方法。 - AechoLiu
这对于视网膜设备不起作用,因为它会裁剪原始图像而不是视网膜屏幕中的表示(即如果320x480是原始图像的正常分辨率,640x960是视网膜分辨率,则CGRect(0,0,320,480)将在视网膜上时裁剪出图像的左上角四分之一)。 - ohcibi
4
为了让这份代码也适用于视网膜屏幕,你需要获取图片的比例因子(image.scale),并将其应用到矩形框中(把所有数值乘以该比例因子),当创建最终的UIImage时,使用方法imageWithCGImage:scale:orientation:来再次设置正确的比例因子。 - Mecki

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!)

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接