Swift 3:绘制矩形

15

我学习Swift才三天,试图找出如何绘制一个矩形。由于还不太了解这门语言,不知道要扩展哪些类或覆盖哪些方法,我已经查看了一些示例代码,但似乎都不起作用(我认为是因为我正在使用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")

    }

}

那样做什么也没用。求助。


如果你刚开始学习编程,不应该在Stack Overflow上问这样的广泛问题。你应该找一本好书或一系列在线教程。看看学习ObjC的好资源;它包括iOS的参考资料,大部分材料现在已经更新为Swift。祝你好运! - jscs
1
  1. 不要自己调用draw方法。
  2. 只需调用view.addSubview(k)将视图添加到您的视图层次结构中,当操作系统需要时,它会为您调用draw方法。
- Rob
4个回答

17
为了查看视图,您需要创建一个并为其设置框架,以便它知道要将其做多大。
如果您将代码放在 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 Touch自动调用以显示视图。 iPhoneSE上的黄色正方形

我收到错误信息:无法在范围内找到“Draw”。 - Doug Null

10

创建一个类,将其放入单独的 Swift 3 文件中。

//
//  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 上运行:

enter image description here

使用 XCode 8.0(8A218a)版本,Swift 3 语言编写,目标 iOS 10.0。


3
draw(_:)文档中:- 您不应该直接调用此方法。要使视图的一部分无效,并导致该部分重新绘制,请调用setNeedsDisplay()setNeedsDisplay(_:)方法。 - bshirley

3
这是绘制矩形的另一种方法, 步骤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)
        }
    }

3

以下是使用 Swift 5 绘制矩形的方法。

首先创建一个绘图类。它使用 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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接