Swift3:绘制矩形

Swift 3: Drawing a rectangle

我刚接触 swift 3 天,我正在尝试弄清楚如何绘制矩形。我对这种语言太陌生了,不知道要扩展的 类 和要覆盖的方法,我四处寻找示例代码,但似乎没有任何效果(我将其归因于我对 swift 3).

我现在正在尝试的是:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()


        let k = Draw(frame: CGRect(
            origin: CGPoint(x: 50, y: 50),
            size: CGSize(width: 100, height: 100)))

        k.draw(CGRect(
            origin: CGPoint(x: 50, y: 50),
            size: CGSize(width: 100, height: 100)));
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
class Draw: 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 h = rect.height
        let w = rect.width
        var color:UIColor = UIColor.yellow()

        var drect = CGRect(x: (w * 0.25),y: (h * 0.25),width: (w * 0.5),height: (h * 0.5))
        var bpath:UIBezierPath = UIBezierPath(rect: drect)

        color.set()
        bpath.stroke()

        print("it ran")

        NSLog("drawRect has updated the view")

    }

}

那什么也没做。帮助。

为了看到视图,您需要创建一个视图并给它框架,这样它就知道该视图有多大。

如果您将代码放在 Playground 中,然后添加此行:

let d = Draw(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

您可以单击右侧的快速查看,然后您将看到该视图。


您还可以在 ViewController 中将视图添加为 view 的子视图,然后您将在 iPhone:

中看到它
override func viewDidLoad() {
    super.viewDidLoad()

    let k = Draw(frame: CGRect(
        origin: CGPoint(x: 50, y: 50),
        size: CGSize(width: 100, height: 100)))

    // Add the view to the view hierarchy so that it shows up on screen
    self.view.addSubview(k)
}

请注意,您永远不会直接调用 draw(_:)。它由 Cocoa 触摸 显示视图。

创建一个class,我把它放在一个单独的Swift3文件中。

//
//  Plot_Demo.swift
//
//  Storyboard is not good in creating self adapting UI
//  Plot_Demo creates the drawing programatically.

import Foundation
import UIKit

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

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

    public override func draw(_ frame: CGRect) {
        let h = frame.height
        let w = frame.width
        let color:UIColor = UIColor.yellow

        let drect = CGRect(x: (w * 0.25), y: (h * 0.25), width: (w * 0.5), height: (h * 0.5))
        let bpath:UIBezierPath = UIBezierPath(rect: drect)

        color.set()
        bpath.stroke()

        print("it ran")
        NSLog("drawRect has updated the view")
    }
}

UIViewController 对象中的使用示例:

override func viewDidLoad() {
    super.viewDidLoad()

    // Instantiate a new Plot_Demo object (inherits and has all properties of UIView)
    let k = Plot_Demo(frame: CGRect(x: 75, y: 75, width: 150, height: 150))

    // Put the rectangle in the canvas in this new object
    k.draw(CGRect(x: 50, y: 50, width: 100, height: 100))

    // view: UIView was created earlier using StoryBoard
    // Display the contents (our rectangle) by attaching it
    self.view.addSubview(k)
}

运行 在 iPhone 模拟器和 iPhone:

已使用 XCode 版本 8.0 (8A218a),Swift 3,目标 iOS 10.0

这是绘制矩形的另一种方式,

第 1 步:获取给定点的矩形路径

(注意:arrPathPoints必须是4个才能画矩形),

func getPathPayer(arrPathPoints:[CGPoint]) throws -> CAShapeLayer {
        enum PathError : Error{
            case moreThan2PointsNeeded
        }

        guard arrPathPoints.count > 2 else {
            throw PathError.moreThan2PointsNeeded
        }

        let lineColor = UIColor.blue
        let lineWidth: CGFloat = 2
        let path = UIBezierPath()
        let pathLayer = CAShapeLayer()

        for (index,pathPoint) in arrPathPoints.enumerated() {
            switch index {
            //First point
            case 0:
                path.move(to: pathPoint)

            //Last point
            case arrPathPoints.count - 1:
                path.addLine(to: pathPoint)
                path.close()

            //Middle Points
            default:
                path.addLine(to: pathPoint)
            }
        }

        pathLayer.path = path.cgPath
        pathLayer.strokeColor = lineColor.cgColor
        pathLayer.lineWidth = lineWidth
        pathLayer.fillColor = UIColor.clear.cgColor

        return pathLayer
    }

第二步:用法,调用方法是这样的,

override func viewDidLoad() {
        super.viewDidLoad()

        do {
            let rectangleLayer = try getPathPayer(arrPathPoints: [
                CGPoint(x: 110, y: 110),    //Top-Left
                CGPoint(x: 130, y: 110),    //Top-Right
                CGPoint(x: 130, y: 130),    //Bottom-Right
                CGPoint(x: 110, y: 130)])   //Bottom-Left
            view.layer.addSublayer(rectangleLayer)
        } catch {
            debugPrint(error)
        }
    }

我的如何使用 Swift 5.

绘制矩形的版本

先创建一个class来做图。它使用 CoreGraphics 进行绘图,而不是 UIKit。

import UIKit

class DrawRectangle: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func draw(_ rect: CGRect) {

        guard let context = UIGraphicsGetCurrentContext() else {
            print("could not get graphics context")
            return
        }

        context.setStrokeColor(UIColor.yellow.cgColor)
        context.setLineWidth(2)
        context.stroke(rect.insetBy(dx: 10, dy: 10))
    }
}

然后将其放入您 ViewController 的 viewDidLoad()

    let myView = DrawRectangle(frame: CGRect(x: 50, y: 50, width: 100, height: 100))

    self.view.addSubview(myView)