首页 > 解决方案 > 如何在图像周围删除 UIGraphicsGetCurrentContext 而不是填充清除或更改上下文的大小 - Swift 4

问题描述

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

图像前

种植区 后像

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

标签: swiftuiimagecore-graphicsuigraphicscontext

解决方案


根据马特的建议,我所需要的只是推到负坐标并从那里开始图像!!所以我所需要的(一旦你有了裁剪矩形)就是这样:

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

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

完整答案在这里 ,他的项目在 这里

谢谢你


推荐阅读