gpt4 book ai didi

ios - Swift drawInRect 无法展开 Optional.None

转载 作者:行者123 更新时间:2023-11-28 05:34:44 25 4
gpt4 key购买 nike

我正在尝试将我的旧代码从 objective-c 转换为 swift。

但是我在 self.image.drawInRect() 上得到以下错误:

fatal error :无法解包 Optional.None

我有一个名为 Canvas 的类,它是 UIImageView 的子类,它在 Storyboard上设置,并在我唯一的 ViewController 上初始化:

init(coder aDecoder: NSCoder!) {
pref = NSUserDefaults.standardUserDefaults()

currentPlay = Play()
canvas = Canvas(coder: aDecoder)
super.init(coder: aDecoder)
}

这是我的 Canvas.Swift

import UIKit

class Canvas: UIImageView {

var path:UIBezierPath = UIBezierPath()
var drawColor:UIColor = UIColor.greenColor()
var lastLocation:CGPoint = CGPoint()

init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}

// handling touches

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
let touch:UITouch = touches.anyObject() as UITouch
lastLocation = touch.locationInView(self.superview)
}

override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
let touch:UITouch = touches.anyObject() as UITouch
let location = touch.locationInView(self.superview)

UIGraphicsBeginImageContext(self.frame.size)
self.image.drawInRect(self.frame)
path = UIBezierPath()
path.lineWidth = 8;
path.lineCapStyle = kCGLineCapRound;
drawColor.setStroke()

path.moveToPoint(CGPointMake(lastLocation.x, lastLocation.y))

path.addLineToPoint(CGPointMake(location.x, location.y))
path.stroke()

self.image = UIGraphicsGetImageFromCurrentImageContext();
lastLocation = location

path.closePath()
UIGraphicsEndImageContext();
}

override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
// nothing yet
}
}

ps:如果我删除 drawInRect 线,如果通过 touchedMoved,我可以暂时获得绘图...但是由于上下文被重置,它不会保留在图像上

最佳答案

UIImageView 通常是用图像初始化的 - 但在您的情况下,您正在取消存档并假设 image 属性包含有效图像。由于 image 属性是隐式展开的(它被定义为 var image: UIImage!),它不会给你一个编译时错误,而是在运行时崩溃。

要打开图像并在图像可用时使用 drawInRectself.image.drawInRect(self.frame) 替换为

if let image = self.image {
image.drawInRect(self.frame)
}

关于ios - Swift drawInRect 无法展开 Optional.None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24562527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com