我不确定从哪里开始,并且正在寻找是否有人可以直接指出我。
我正在建立在以下项目之上: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)
。