如何在 UIColor 中使用变量?
Posted
技术标签:
【中文标题】如何在 UIColor 中使用变量?【英文标题】:How do I use variables in a UIColor? 【发布时间】:2015-05-18 18:00:14 【问题描述】:我应该为 UIColor() 使用什么类型的变量和 为什么这段代码不起作用? 我正在尝试使用在不同类中创建的变量作为红色、绿色和蓝色的数量。我对所有颜色都做了相同的变量,但得到了错误:'extra argument green in call'
import UIKit
class Color: UIView
var colors = ViewController()
override func drawRect(rect: CGRect)
let swiftColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1);
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 5.0)
CGContextSetStrokeColorWithColor(context,
UIColor(red: CGFloat(colors.red1), green: CGFloat(colors.green1), blue: CGFloat(colors.blue1), alpha: 1.0))
let rectangle = CGRectMake(60,170,200,80)
CGContextAddRect(context, rectangle)
CGContextStrokePath(context)
CGContextSetFillColorWithColor(context,
UIColor(red: CGFloat(colors.red1), green: CGFloat(colors.green1), blue: CGFloat(colors.blue1), alpha: 1.0))
CGContextFillRect(context, rectangle)
【问题讨论】:
给 UIColor(red: CGFloat(colors.red1), green: CGFloat(colors.green1), blue: CGFloat(colors.blue1), alpha: 1.0)).CGColor 【参考方案1】:试试这个。
class Color: UIView
var colors = ViewController()
override func drawRect(rect: CGRect)
let swiftColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1);
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 5.0)
CGContextSetStrokeColorWithColor(context,
UIColor(red: CGFloat(colors.red1), green: CGFloat(colors.green1), blue: CGFloat(colors.blue1), alpha: 1.0).CGColor)
let rectangle = CGRectMake(60,170,200,80)
CGContextAddRect(context, rectangle)
CGContextStrokePath(context)
CGContextSetFillColorWithColor(context,
UIColor(red: CGFloat(colors.red1), green: CGFloat(colors.green1), blue: CGFloat(colors.blue1), alpha: 1.0).CGColor)
CGContextFillRect(context, rectangle)
CGContextSetStrokeColorWithColor
需要 CGColor
作为参数,但您提供的是 UIColor
。
【讨论】:
UIColor(red: CGFloat(colors.red1), green: CGFloat(colors.green1), blue: CGFloat(colors.blue1), alpha: 1.0).CGColor 将 .CGColor 添加到颜色以上是关于如何在 UIColor 中使用变量?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 c# 在 Xamarin.Ios 中将 UIColor 转换为字符串和字符串转换为 UIColor
在swift中使用UIColor(patternImage:UIImage(named:“myimage.jpg”))设置背景时如何获取视图的背景颜色或图像