我正在编写一个简单的绘图应用程序,每次用户将手指放下来绘制时,都会使用不同的颜色。如果我设置我的"红色,绿色,蓝色"值到特定值,然后它绘制它应该,但当我尝试使用CGFloat随机函数时,应用程序似乎忽略用户输入。我验证了随机函数功能只是在生成随机值时打印出来。
如果我发表评论,请在下面的代码中
red = randomCGFloat(min: 1, max: 254)
green = randomCGFloat(min: 1, max: 254)
blue = randomCGFloat(min: 1, max: 254)
并在setStrokeColor中使用默认值0表示红色,绿色,蓝色,然后绘图应用程序通常使用黑色作为笔触颜色。如果我取消注释随机数发生器,那么当我尝试绘制时应用程序不会显示任何内容。随机化器的限制设置正确(并在打印输出消息中验证),因此我不确定为什么setStrokeColor忽略这些值。
import UIKit
import Foundation
class ViewController: UIViewController {
@IBOutlet weak var mainImageView: UIImageView!
var lastPoint = CGPoint.zero
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var brushWidth: CGFloat = 30.0
var opacity: CGFloat = 1.0
var swiped = false
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
swiped = false
red = randomCGFloat(min: 1, max: 254)
green = randomCGFloat(min: 1, max: 254)
blue = randomCGFloat(min: 1, max: 254)
print("red: \(red)")
print("green: \(green)")
print("blue: \(blue)")
if let touch = touches.first {
lastPoint = touch.location(in: self.view)
}
}
func drawLineFrom(from fromPoint: CGPoint, to toPoint: CGPoint) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)
mainImageView.image?.draw(in: view.bounds)
let context = UIGraphicsGetCurrentContext()
context?.move(to: fromPoint)
context?.addLine(to: toPoint)
context?.setLineCap(CGLineCap.round)
context?.setLineWidth(brushWidth)
context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
context?.setBlendMode(CGBlendMode.normal)
context?.strokePath()
mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
mainImageView.alpha = opacity
UIGraphicsEndImageContext()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
swiped = true
if let touch = touches.first {
let currentPoint = touch.location(in: view)
drawLineFrom(from: lastPoint, to: currentPoint)
lastPoint = currentPoint
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if !swiped {
// draw a single point
self.drawLineFrom(from: lastPoint, to: lastPoint)
}
}
func randomCGFloat(min: CGFloat, max: CGFloat) -> CGFloat {
return round(CGFloat(Float(arc4random()) / Float(UINT32_MAX)) * (max - min) + min)
}
任何建议都将不胜感激!
答案 0 :(得分:1)
传递给setStrokeColor的红色/绿色/蓝色值需要介于0.0和1.0之间,而不是代码中的1到254.