如何通过其他方向重绘CGgraphics?

How to redraw CGgraphics by other orientation?

我有 UIView class 在视图上显示线条:

import UIKit

class DrawLines: UIView
{
    override init(frame: CGRect)
    {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder)
    {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw( _ rect: CGRect)
    {
        let context = UIGraphicsGetCurrentContext()
        context!.setLineWidth(2.0)
        context!.setStrokeColor(UIColor.white.cgColor)

        //make and invisible path first then we fill it in
        context!.move(to: CGPoint(x: 0, y: 0))
        context!.addLine(to: CGPoint(x: self.bounds.width, y:self.bounds.height))
        context!.strokePath()
    }
}

然后主要 class 调用它...

import UIKit

class GraphViewController: UIViewController
{
    @IBOutlet weak var graphView: UIView!
    override func viewDidLoad()
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let draw = DrawLines(frame: self.graphView.bounds)
        view.addSubview(draw)
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        if UIDevice.current.orientation.isLandscape
        {
            print("landscape")
        }
        else
        {
            print("portrait")
        }
    }
}

但是,当我旋转屏幕时出现问题。据我了解,问题是 - 它总是使用屏幕的高度和宽度,所以我应该检查横向并放置:

let yLandscaped = self.bounds.width
let xLandscaped = self.bounds.height

但是我不知道,如何清除视图中的所有行?

当我尝试旋转时 - 据我所知,它需要以前的视野。这样我就颠倒了 X 和 Y 的观点。但是当你第一次加载它时,它应该只是 view.bounds。但是我试图将图像的高度切割为-10及其以下,应该有一个空的space,但是在它被转动之前有一部分相同的图像!要修复它,只需要把

while let subview = self.view.subviews.last
        {   subview.removeFromSuperview()   }

每次轮换之前。效果很好!

override func viewDidLoad()
{
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let draw = DrawLines(frame: self.view.bounds)
    view.addSubview(draw)
}

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape
    {
        print("landscape")
        while let subview = self.view.subviews.last
        {   subview.removeFromSuperview()   }
        let draw = DrawLines(frame: CGRect(x: self.view.bounds.origin.y, y: self.view.bounds.origin.x, width: self.view.bounds.height, height: self.view.bounds.width))
        view.addSubview(draw)
    }

    else
    {
        print("portrait")
        while let subview = self.view.subviews.last
        {   subview.removeFromSuperview()   }
        let draw = DrawLines(frame: CGRect(x: self.view.bounds.origin.y, y: self.view.bounds.origin.x, width: self.view.bounds.height, height: self.view.bounds.width))
        view.addSubview(draw)
    }
}