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

问题描述 投票:0回答:1

enter image description here

enter image description here

我有UIView类来显示视图上的行:

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()
    }
}

和主要类别称之为......

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

但我不知道,如何清除视图内的所有线条?

ios swift4 bounds
1个回答
0
投票

当我试图旋转时 - 它按照我的理解需要先前的视角。所以我颠倒了X和Y的起源。但是当你首先加载它时它应该只是view.bounds。然而,我试图削减图像-10及其下方的高度,应该有一个空的空间,但在它被转动之前有一部分相同的图像!要解决它,只需要把它

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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.