嘿伙计们,所以我正在使用苹果笔在应用程序上工作,并且周围没有太多资源,所以希望有人可以提供帮助。
我的应用程序做的是让用户使用苹果笔,UIImage视图和核心图形绘制图像以创建上下文等。我现在希望能够使用NSData保存用户理想的绘制内容,但是由于它被保存为PNG,我如何能够加载该保存的文件并再次在UIImage屏幕上获取它?
谢谢!
这是我的核心图形代码:
let π = CGFloat(M_PI)
class NoteCanvasView: UIImageView {
private var defaultLineWidth:CGFloat = 1
private var drawColor: UIColor = UIColor.blackColor()
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else { return }
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
// Draw previous image into context
image?.drawInRect(bounds)
drawStroke(context, touch: touch)
// Update image
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
private func drawStroke(context: CGContext?, touch: UITouch) {
let previousLocation = touch.previousLocationInView(self)
let location = touch.locationInView(self)
// Calculate line width for drawing stroke
let lineWidth = lineWidthForDrawing(context, touch: touch)
// Set color
drawColor.setStroke()
// Configure line
CGContextSetLineWidth(context, lineWidth)
CGContextSetLineCap(context, .Round)
// Set up the points
CGContextMoveToPoint(context, previousLocation.x, previousLocation.y)
CGContextAddLineToPoint(context, location.x, location.y)
// Draw the stroke
CGContextStrokePath(context)
}
private func lineWidthForDrawing(context: CGContext?, touch: UITouch) -> CGFloat {
var lineWidth = defaultLineWidth
return lineWidth
}
func saveNote(){
let data = UIImagePNGRepresentation(image!)
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(data, forKey: "test123")
userDefaults.synchronize()
}
func retrieveNote(){
if let data = NSUserDefaults.standardUserDefaults().dataForKey("test123"),let image = UIImage(data: data){
}
}
func setStrokeColor(color: UIColor){
drawColor = color
}
func setStrokeWidth(size: CGFloat){
defaultLineWidth = size
}
func clearCanvas(animated animated: Bool) {
if animated {
UIView.animateWithDuration(0.2, animations: {
self.alpha = 0
}, completion: { finished in
self.alpha = 1
self.image = nil
})
} else {
image = nil
}
}
}
答案 0 :(得分:0)
你可以从像
这样的数据中获取图像 UIImage(data:imageData,scale:1.0)
获取UIImage
引用并获取此类图片,您可以在imageview
上显示该图片
希望这会有所帮助:)
答案 1 :(得分:-1)
您可以将其保存并检索为NSData。我还不确定什么是处理草图的最佳方法,我认为NSData也是如此。会尝试并告诉你。