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



我真的不确定从哪里开始,正在寻找是否有人可以直接指出我。

我正在以下项目之上构建: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)

任何帮助为我指明正确方向将不胜感激,因为我似乎无法使任何事情发挥作用!

在你的 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)使用它.

最新更新