iOS-当前视图控制器内的快速绘制形状

iOS-当前视图控制器内的快速绘制形状,ios,swift,xcode,shapes,Ios,Swift,Xcode,Shapes,我真的不确定从哪里开始,我一直在寻找是否有人能直接为我指出正确的方向 我在以下项目的基础上进行建设: 我的目标是能够在屏幕的中间画一个大矩形,它显示串行消息SerialVIEW控制器。SWIFT [稍后我将删除这些消息,因为它们是用于调试目的的剩余部分]并且能够独立地为矩形的上半部分和下半部分着色。当消息达到某个条件时,这些将被设置,我已经实现了 我希望能够使用以下函数操作矩形的上半部分和下半部分: func uiColorFromHex(rgbValue: Int) -> UIColor

我真的不确定从哪里开始,我一直在寻找是否有人能直接为我指出正确的方向

我在以下项目的基础上进行建设:

我的目标是能够在屏幕的中间画一个大矩形,它显示串行消息SerialVIEW控制器。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)

如果有人能帮我指出正确的方向,我将不胜感激,因为我似乎什么都做不到

在您的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)
    }
}

然后通过让color=UIColorfromHexValue:10使用它。

谢谢!