Swift

iOS 서명 기능 만들기_2

반다이크 2022. 4. 12. 10:01
반응형

1. Canvas View 코드

 

class Canvas: UIView {

    fileprivate var strokeColor = UIColor.black
    fileprivate var strokeWidth: Float = 2

    func setStrokeWidth(width: Float) {
        self.strokeWidth = width
    }

    func setStrokeColor(color: UIColor) {
        self.strokeColor = color
    }

    func undo() {
        _ = lines.popLast()
        setNeedsDisplay()
    }

    func clear() {
        lines.removeAll()
        setNeedsDisplay()
    }

    fileprivate var lines = [Line]()

    override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        guard let context = UIGraphicsGetCurrentContext() else { return }

        lines.forEach { (line) in
            context.setStrokeColor(line.color.cgColor)
            context.setLineWidth(CGFloat(line.strokeWidth))
            context.setLineCap(.butt)
            for (i, p) in line.points.enumerated() {
                if i == 0 {
                    context.move(to: p)
                } else {
                    context.addLine(to: p)
                }
            }
            context.strokePath()
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        lines.append(Line.init(strokeWidth: strokeWidth, color: strokeColor, points: []))
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let point = touches.first?.location(in: self) else { return }
        guard var lastLine = lines.popLast() else { return }
        lastLine.points.append(point)
        lines.append(lastLine)
        setNeedsDisplay()
    }
}

 

#처음 터치한 좌표를 기준으로 추가 좌표와 색상, 넓이에 대한 데이터를 배열에 저장해 나가는 방식

 

2. Line 구조체 

struct Line {
    let strokeWidth: Float
    let color: UIColor
    var points: [CGPoint]
}

 

# 선에 대한 정보

 

3. 스토리보드 구성

 

 

#싸인패드로 사용할 뷰

#사진 저장, 클리어 버튼

#변환된 싸인 이미지 확인할 이미지뷰

 

4. 객체 연결

 

5. ViewController 구성

 

## ConvertImage

     - UIView를 Image로 반환

## didFinishSavingWithError

     - 사진첩에 저장

 

 

6. 싸인 확인

 

반응형

'Swift' 카테고리의 다른 글

iOS GoogleService - Info 타겟 분리(FCM, Crashlytics)  (0) 2022.05.02
iOS 타겟 분리  (2) 2022.05.02
iOS Navigation RootView 설정  (0) 2022.04.08
iOS 서명 기능 만들기_1  (2) 2022.04.05
iOS Firebase Crashlytics  (0) 2022.03.25