При добавлении нескольких строк через для l oop с использованием UIBezierPath толщина линий не унифицирована? - PullRequest
1 голос
/ 16 июня 2020

Я создал небольшой проект ios, используя swift 5, и создал небольшой UIView, и мне нужно добавить вертикальные линии в UIView. Я создал UIBezierPath рядом с l oop и повторил строку. Линии нарисованы правильно в соответствии с заданными координатами x, y, но я могу изменить толщину линии, некоторые из них жирные, а некоторые размытые (тонкие). Если кто-то знает, что здесь происходит, пожалуйста, помогите мне решить эту проблему и высоко оцените ваш отзыв. Пожалуйста, укажите мой код и изображение, например,

Код:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let testView = UIView(frame: CGRect(x:0, y: 0, width: 300, height: 500))
        testView.backgroundColor = UIColor.blue
        self.view.addSubview(testView)

        testView.translatesAutoresizingMaskIntoConstraints = false
        let guide = self.view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            testView.topAnchor.constraint(equalTo: guide.topAnchor, constant: 300),
            testView.leftAnchor.constraint(equalTo: guide.leftAnchor, constant: 300),
            testView.widthAnchor.constraint(equalToConstant: 300),
            testView.heightAnchor.constraint(equalToConstant: 500)
        ])

        let lineDistance:Int = 20
        let lineColor:UIColor = UIColor.white
        let gridPath = UIBezierPath()
        gridPath.lineWidth = 2

        var count = 0
        for x in 0..<Int(testView.bounds.size.width) {
            if x % lineDistance == 0 {
                count += 1
                gridPath.move(to: CGPoint(x: CGFloat(x), y: 0))
                gridPath.addLine(to: CGPoint(x: CGFloat(x), y: testView.bounds.size.height))
            }
        }
        print("no of execution \(count)")

        //        for y in 0..<Int(testView.bounds.size.height) {
        //            if y % lineDistance == 0 {
        //                gridPath.move(to: CGPoint(x:0, y: CGFloat(y)))
        //                gridPath.addLine(to: CGPoint(x: testView.bounds.size.width, y: CGFloat(y)))
        //            }
        //        }
        gridPath.close()
        let layer = CAShapeLayer()
        layer.path = gridPath.cgPath
        gridPath.stroke()
        layer.strokeColor = lineColor.cgColor

        testView.layer.insertSublayer(layer, at: 0)
    }


}

Изображение: output image

1 Ответ

0 голосов
/ 16 июня 2020
• 1000 просто протестировал его, и он отлично работает:
import UIKit

class ViewController: UIViewController {

    private let gridView: GridView = {
        $0.backgroundColor = UIColor.white
        $0.translatesAutoresizingMaskIntoConstraints = false
        return $0
    }(GridView(lineDistance: 20, lineWidth: 3, lineColor: .black))

    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }

    private func setup() {
        setupViews()
        setupConstraints()
    }

    private func setupViews() {
        view.addSubview(gridView)
    }

    private func setupConstraints() {
        NSLayoutConstraint.activate([
             gridView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
             gridView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
             gridView.widthAnchor.constraint(equalToConstant: 300),
             gridView.heightAnchor.constraint(equalToConstant: 500)
         ])
    }
}

class GridView: UIView {

    let lineDistance: Int
    let lineWidth: CGFloat
    let lineColor: UIColor

    init(lineDistance: Int, lineWidth: CGFloat, lineColor: UIColor) {
        self.lineDistance = lineDistance
        self.lineWidth = lineWidth
        self.lineColor = lineColor
        super.init(frame: .zero)
    }

    required init?(coder: NSCoder) {
        fatalError()
    }

    override func draw(_ rect: CGRect) {
        drawGrid(rect)
    }

    private func drawGrid(_ rect: CGRect) {
        let linePath = UIBezierPath()
        for x in 0..<Int(rect.size.width) {
            if x % lineDistance == 0 {
                let topPoint =  CGPoint(x: CGFloat(x), y: 0)
                let bottomPoint = CGPoint(x: CGFloat(x), y: rect.size.height)
                linePath.move(to: topPoint)
                linePath.addLine(to: bottomPoint)
            }
        }
        let lineLayer = CAShapeLayer()
        lineLayer.path = gridPath.cgPath
        lineLayer.lineWidth = lineWidth
        lineLayer.strokeColor = lineColor.cgColor
        layer.addSublayer(lineLayer)
    }
}
...