티스토리 뷰

Develop/iOS

[iOS] Swift 도형 그리기

Nebori 2018. 7. 29. 19:47

UIBezierPath

import UIKit

var x = 0
var y = 0
var width = 100
var height = 100        

// Initialize the path.
var path = UIBezierPath()

var circle = UIBezierPath(ovalIn: CGRect(x: width/2 - height/2,
                                        y: 0,
                                        width: height,
                                        height: height))

사각형

import UIKit

var x = 0
var y = 0
var width = 100
var height = 100        

// Initialize the path.
var path = UIBezierPath()

// Specify the point that the path should start get drawn.
path.move(to: CGPoint(x: x, y: y))

// Create a line between the starting point and the bottom-left side of the view.
path.addLine(to: CGPoint(x: x, y: height))

// Create the bottom line (bottom-left to bottom-right).
path.addLine(to: CGPoint(x: width, y: height))

// Create the vertical line from the bottom-right to the top-right side.
path.addLine(to: CGPoint(x: width, y: y))

// Close the path. This will create the last line automatically.
path.close()
let circle: UIBezierPath = UIBezierPath(ovalIn:
                                        CGRect(x: CGFloat(50.0),
                                               y: CGFloat(self.frame.height/3),
                                               width: CGFloat(self.frame.height/4),
                                               height: CGFloat(self.frame.height/4)))

let aPath = UIBezierPath()
aPath.move(to: CGPoint(x: CGFloat(50.0 + self.frame.height/8), y: self.frame.height/3))
aPath.addLine(to: CGPoint(x: CGFloat(50.0 + self.frame.height/8), y: self.frame.height))

CAShapeLayer

let shape = CAShapeLayer()
shape.lineWidth = 3 // 라인 굵기는 3
shape.path = circle.cgPath // 해당 경로는 위 circle을 사용
shape.strokeColor = UIColor.black.cgColor // 외부 경계선은 검정색
shape.fillColor = UIColor.clear.cgColor // 내부 색은 비우고
self.layer.addSublayer(shape) // 해당 레이어를 서브로 추가

animation

// 선 그리기
let aPath = UIBezierPath()
aPath.move(to: CGPoint(x: CGFloat(50.0 + self.frame.height/8), y: self.frame.height/3))
aPath.addLine(to: CGPoint(x: CGFloat(50.0 + self.frame.height/8), y: self.frame.height))

// 애니메이션 추가
let animation = CABasicAnimation(keyPath: "strokeEnd")
// 그린 선의 어디서부터 시작할지
animation.fromValue = 0
// 애니메이션 그리는 시간
animation.duration = 1
// 그려진 레이어에 애니메이션을 추가
shapreLayer.add(animation, forKey: "MyAnimation")


'Develop > iOS' 카테고리의 다른 글

[SwiftBook] 타입 1/2  (0) 2018.09.19
[SwiftBook] 값  (0) 2018.09.18
[iOS] Swift Codable  (0) 2018.09.09
[iOS] Swift QRCode 읽기  (0) 2018.08.26
[iOS Developer Program] iOS 개인 개발자 등록  (0) 2018.02.26
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31