我想知道如何像在电话上一样保存我的应用程序的图形,然后将其发送到服务器。
这是我的代码。
我在这堂课上画画。
import Foundation
import UIKit
class Sign: UIViewController
{
@IBOutlet weak var btnSave: UIButton!
@IBOutlet weak var btnClear: UIButton!
let canvas = Canvas()
fileprivate func setupLayout() {
let stackView = UIStackView(arrangedSubviews: [btnClear,btnSave])
view.addSubview(stackView)
stackView.distribution = .fillEqually
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
override func viewDidLoad() {
view.addSubview(canvas)
canvas.backgroundColor = .white
canvas.frame = view.frame
setupLayout()
}
@IBAction func ClearCanvas(_ sender: Any) {
canvas.clear()
}
@IBAction func SaveCanvas(_ sender: Any) {
}
}
我也有这个Canvas类,其中有按钮的功能。 只想知道如何处理我的视图或将其与绘图转换为图像并将其保存,然后将其发送到服务器。
import Foundation
import UIKit
class Canvas: UIView {
func clear(){
lines.removeAll()
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {return}
context.setStrokeColor(UIColor.black.cgColor)
context.setLineWidth(5)
context.setLineCap(.butt)
lines.forEach { (line) in
for (i , p) in line.enumerated(){
if i == 0 {
context.move(to: p)
} else {
context.addLine(to: p)
}
}
}
context.strokePath()
}
var lines = [[CGPoint]]()
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
lines.append([CGPoint]())
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let point = touches.first?.location(in: nil) else {return}
guard var lastline = lines.popLast() else { return }
lastline.append(point)
lines.append(lastline)
setNeedsDisplay()
}
}
答案 0 :(得分:2)
您可以在类Canvas
中添加一个函数来绘制图像并将图像数据更新到服务器。
func screenShot() -> UIImage? {
//Create the UIImage
UIGraphicsBeginImageContext(self.frame.size)
self.layer.renderInContext(UIGraphicsGetCurrentContext())
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
答案 1 :(得分:0)
当您在名为Canvas的视图中绘制了所有内容后,为什么不将其转换为像截图一样的图像呢?
以下是UIView的扩展,具有名为屏幕快照的计算属性,它将为您提供所需的图像:-
extension UIView {
var screenshot : UIImage? {
var screenshot :UIImage?
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
guard let context = UIGraphicsGetCurrentContext() else {return nil}
layer.render(in:context)
screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return screenshot
}
}
使用方法:-
@IBAction func SaveCanvas(_ sender: Any) {
let drawing = canvas.screenshot
//Now send this image to server
}