如何删除图像周围的UIGraphicsGetCurrentContext而不是填充清除或更改上下文的大小 - Swift 4

时间:2018-06-19 01:03:50

标签: swift uiimage core-graphics uigraphicscontext

UIGraphicsBeginImageContextWithOptions(startingImageL.size, false, 0.0) 
    let context = UIGraphicsGetCurrentContext()!

    startingImageL.draw(in: CGRect(origin: CGPoint.zero, size: startingImageL.size), blendMode: .copy, alpha: 1.0)

    context.setBlendMode(.copy)
    context.setFillColor(UIColor.clear.cgColor)

    let rectPath = UIBezierPath(rect:  CGRect(origin: CGPoint.zero, size: startingImageL.size))
    let cropRectPath = UIBezierPath(rect: cropZone)

    print("cropRectPath \(cropRectPath.debugDescription) ")
    print("cropZone \(cropZone.debugDescription) ")

    print("cropZone width \(cropZone.width) ")
    print("cropZone height \(cropZone.height) ")

    print("cropZone maxX \(cropZone.maxX) ")
    print("cropZone maxY \(cropZone.maxY) ")


    rectPath.append(cropRectPath)
    rectPath.usesEvenOddFillRule = true

    context.saveGState()
    rectPath.fill()
    context.clip(to: cropZone)
//        UIRectClip(cropZone) <-nope
//        UIRectFrame(cropZone) <- nope
//        rectPath.addClip() <nope

在图像之前

cropping zone after image

它的收获效果很好但是我希望它删除它周围的所有空间而不是填充(粉红色)然后图像会填满视图。谢谢!

1 个答案:

答案 0 :(得分:0)

Per Matt的建议我所需要的只是推动负坐标并在那里开始图像!所以我需要的(一旦你有裁剪矩形)是这样的:

    UIGraphicsBeginImageContextWithOptions(cropZone.size, false, 0.0)
    UIGraphicsGetCurrentContext()

    startingImageL.draw(at: CGPoint(x:-cropZone.origin.x,
                                     y:-cropZone.origin.y))
    let result = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

Complete answer here他的项目是here

谢谢你