ios - 如何使用 Swift 在 iOS 中刷新/重绘/重新加载 UIGraphicsImageRenderer

标签 ios swift swift3 uiview

我有一个自定义的 UIView 类,它使用 UIGraphicsImageRenderer 绘制一些线条,我有一些 slider 来更改用于绘制线条的点,但这样做并没有不要删除旧线,它只是在它们上面绘制新线。我试过在方法的顶部和底部附近添加 self.setNeedsDisplay(),两者都没有任何区别。

我从 hackingwithswift project 27 中了解了如何使用 UIGraphicsImageRenderer 的基本概念- 在那个项目中,他使用 switch 语句调用不同的函数来绘制不同的东西,这似乎可以很好地清除和重绘东西。

我也尝试过 var clearsContextBeforeDrawing: Bool = true,但我认为我没有正确使用它,我在文档中找到了它。

我还在 setNeedsDisplay 文档中看到它说“您应该使用此方法请求仅当 View 的内容或外观发生变化时才重绘 View 。如果您只是更改 View , View 通常不会重绘”—我猜测“ View 的几何形状”是指转换(缩放/平移/旋转)之类的东西?

func drawLines(pointList: [CGPoint],
               cycle: Bool = false,
               lineColor: CGColor = UIColor.blue.cgColor,
               fillColor: CGColor = UIColor.clear.cgColor) {

//        self.setNeedsDisplay()
    let renderer = UIGraphicsImageRenderer(size: CGSize(width: 728, height: 984))
//        var clearsContextBeforeDrawing: Bool = true
    let img = renderer.image { ctx in
        ctx.cgContext.move(to: pointList[0])

        for v in pointList.dropFirst() {
            ctx.cgContext.addLine(to: v)
        }

        ctx.cgContext.setStrokeColor(lineColor)
        ctx.cgContext.strokePath()
    }

    let iv = UIImageView(image:img)
    iv.frame.origin = CGPoint(x: 0, y: 0)
    self.addSubview(iv)
//        self.setNeedsDisplay()
}

最佳答案

每次调用 drawLines() 时,您都会添加一个新的 UIImageView。您的代码编写方式,每个 ImageView 都有清晰的背景...因此您会看到“线条”彼此叠加。

您应该已经将一个 UIImageView 添加到self(我们称它为theDrawingImageView),并且然后更改您的函数以结束:

    //let iv = UIImageView(image:img)
    //iv.frame.origin = CGPoint(x: 0, y: 0)
    //self.addSubview(iv)

    theDrawingImageView.image = img
}

编辑:这是一个完整的演示。您可以直接在 playground 页面中运行它。

它创建一个 View Controller 并添加一个 UIButton 和一个 UIImageView。每次点击按钮时,将生成一组 12 个随机点并用于在新的 UIImage 上绘制线条,然后用于设置 .image 属性 ImageView 。

import UIKit
import PlaygroundSupport

class TestViewController : UIViewController {


    let theDrawingImageView: UIImageView = {
        let v = UIImageView()
        v.backgroundColor = UIColor.lightGray
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    let btn: UIButton = {
        let b = UIButton()
        b.setTitle("Tap to Draw Lines", for: .normal)
        b.backgroundColor = .red
        b.translatesAutoresizingMaskIntoConstraints = false
        return b
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor(red: 0.25, green: 0.5, blue: 1.0, alpha: 1.0)

        // add button and image view to self.view
        self.view.addSubview(btn)
        self.view.addSubview(theDrawingImageView)

        // button position
        btn.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        btn.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20.0).isActive = true

        // image view position
        theDrawingImageView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        theDrawingImageView.topAnchor.constraint(equalTo: btn.bottomAnchor, constant: 20.0).isActive = true

        // image view width and height
        theDrawingImageView.widthAnchor.constraint(equalToConstant: 300.0).isActive = true
        theDrawingImageView.heightAnchor.constraint(equalToConstant: 300.0).isActive = true

        // add a target for the button tap
        btn.addTarget(self, action: #selector(btnTapped(_:)), for: .touchUpInside)

    }

    // simple random number function
    func random(_ range:Range<Int>) -> Int {
        return range.lowerBound + Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound)))
    }

    func btnTapped(_ sender: Any) {

        var pts = [CGPoint]()

        let maxX = Int(theDrawingImageView.bounds.size.width)
        let maxY = Int(theDrawingImageView.bounds.size.height)

        // generate a set of 12 random points
        for _ in 1...12 {
            let x = random(0..<maxX)
            let y = random(0..<maxY)
            let pt = CGPoint(x: x, y: y)
            pts.append(pt)
        }

        drawLines(imageView: theDrawingImageView, pointList: pts)

    }

    func drawLines(imageView: UIImageView,
                   pointList: [CGPoint],
                   cycle: Bool = false,
                   lineColor: CGColor = UIColor.blue.cgColor,
                   fillColor: CGColor = UIColor.clear.cgColor) {

        let renderer = UIGraphicsImageRenderer(size: imageView.bounds.size)

        // this creates a new UIImage and draws lines on it
        let img = renderer.image { ctx in

            ctx.cgContext.move(to: pointList[0])

            for v in pointList.dropFirst() {
                ctx.cgContext.addLine(to: v)
            }

            ctx.cgContext.setStrokeColor(lineColor)
            ctx.cgContext.strokePath()

        }

        // set the image view's .image to the new image with the lines drawn on it
        imageView.image = img
    }

}

let vc = TestViewController()
PlaygroundPage.current.liveView = vc

关于ios - 如何使用 Swift 在 iOS 中刷新/重绘/重新加载 UIGraphicsImageRenderer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46078906/

相关文章:

swift - 非 -'@objc' 方法不满足 '@objc' 协议(protocol)的可选要求

Swift 3/IQKeyboardManager : How do you change background color of toolbar , 完成颜色,箭头颜色?

ios - 属性在 UIView 类中不起作用

ios - 将字典键与数组进行比较以提取匹配和不匹配的数据

swift - 我们如何从 Apple TV App 打开 Apple TV 商店

ios - 将手势识别器添加到 UIWindow 上添加的 View 中

ios - 是否需要删除断点 ipa 文件才能在 Ad hoc/Development/app store ipa 文件上运行?

objective-c - MPMediaItemPropertyIsCloudItem是否需要iOS 6运行时?

iOS13分享表: how to set preview thumbnail when sharing UIImage

iphone - 核心数据限制以及何时不持久保存数据