iOS-当前视图控制器中的Swift绘制形状

时间:2018-09-17 05:49:59

标签: ios swift xcode shapes

我不太确定从哪里开始,并且在寻找是否有人可以指出我正确的方向。

我在以下项目之上构建:https://github.com/hoiberg/HM10-BluetoothSerial-iOS

我的目标是能够在屏幕中间的框的顶部绘制一个大矩形,以显示串行消息(SerialViewController.swift)[我稍后将删除这些消息,因为它们仍保留用于调试目的]并能够分别为矩形的上半部和矩形的下半部着色(这些将在消息达到一定条件时设置(我已经实现)。

我希望能够使用以下功能来操纵矩形的上半部分和下半部分:

func uiColorFromHex(rgbValue: Int) -> UIColor {

// &  binary AND operator to zero out other color values
// >>  bitwise right shift operator
// Divide by 0xFF because UIColor takes CGFloats between 0.0 and 1.0

let red =   CGFloat((rgbValue & 0xFF0000) >> 16) / 0xFF
let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 0xFF
let blue =  CGFloat(rgbValue & 0x0000FF) / 0xFF
let alpha = CGFloat(1.0)

return UIColor(red: red, green: green, blue: blue, alpha: alpha)

}

因此,我可以分别控制区域的颜色。即:

let myColorValue = 10

self.topHalfRectangle.hexStringToUIColor(myColorValue)

任何帮助我指出正确方向的帮助将不胜感激,因为我似乎什么也做不了!

1 个答案:

答案 0 :(得分:0)

在您的ViewController中尝试...

// Set a couple of constants to hold the shapes

let topHalfRectangle = CAShapeLayer()
let bottomHalfRectangle = CAShapeLayer()

override func viewDidLoad() {
    super.viewDidLoad()

    // Create shape layer paths for the top and bottom rectangles
    // Note that these will fill the entire view,
    // inset as necessary.
    topHalfRectangle.path = UIBezierPath(rect: CGRect(x: 0.0, y: 0.0, width: view.frame.size.width, height: view.frame.midY)).cgPath
    bottomHalfRectangle.path = UIBezierPath(rect: CGRect(x: 0.0, y: view.frame.midY, width: view.frame.size.width, height: view.frame.midY)).cgPath

    // Add the shape layers to the view
    view.layer.addSublayer(topHalfRectangle)
    view.layer.addSublayer(bottomHalfRectangle)
}

设置颜色:

topHalfRectangle.fillColor = uiColorFromHex(myColorValue).cgColor

顺便说一句,从十六进制值设置UIColor是一项常见任务,因此,我建议扩展UIColor以提供此功能。

import UIKit

extension UIColor {

    /// Create color from RGB hex
    ///
    /// - Parameter fromHexValue: Hexadecimal integer value

    convenience init(fromHexValue: Int) {

        // &  binary AND operator to zero out other color values
        // >>  bitwise right shift operator
        // Divide by 0xFF because UIColor takes CGFloats between 0.0 and 1.0

        let red =   CGFloat((fromHexValue & 0xFF0000) >> 16) / 0xFF
        let green = CGFloat((fromHexValue & 0x00FF00) >> 8) / 0xFF
        let blue =  CGFloat(fromHexValue & 0x0000FF) / 0xFF
        let alpha = CGFloat(1.0)

        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }
}

然后由let color = UIColor(fromHexValue: 10)使用它。