코인 날짜별 종가 차트 구현 - Team-Nogari/Huhoe GitHub Wiki
차트 위키
Charts 라이브러리를 사용하지 않고 코인 날짜별 종가 차트를 구현했습니다.
구현 방향
-
스토리보드 구성
- 스크롤 뷰 내부에
차트 이미지 뷰(UIImageView)
,Floating View(날짜, 가격)
구성했습니다.
- 스크롤 뷰 내부에
-
차트 이미지 뷰 크기 및 X축, Y축 단위 설정
- 차트 이미지 뷰의 크기를 설정합니다. 한 화면에 30일 분량의 차트를 그리기 위해
UIScreen.main.bounds.width / 30
하여X축 단위
를 구했습니다. - 위 단계에서 구현한
X축 단위 * 데이터의 개수(상장 후 현재까지의 일[day] 수)
로 차트 이미지 뷰의 크기를 설정했습니다. Y축 단위
는 차트 이미지 뷰의 높이에서가격 데이터(Array[Double])
의 최소값과 최대값의 차이를 나눠 구했습니다.
- 차트 이미지 뷰의 크기를 설정합니다. 한 화면에 30일 분량의 차트를 그리기 위해
-
차트 이미지 뷰 CGContext 설정
UIGraphicsBeginImageContext(layer.frame.size) let context = UIGraphicsGetCurrentContext() // Path 설정 context?.beginPath() context?.setLineCap(.round) context?.setLineJoin(.round) context?.setLineWidth(CGFloat(5)) context?.setStrokeColor(UIColor.red.cgColor) context?.setShadow(offset: CGSize(width: -2, height: 2), blur: 0, color: UIColor.black.cgColor)
-
차트 그리기
- 차트 이미지 뷰로 넘어온
가격 데이터(Array[Double])
를 한번 더 가공했습니다.
let simplifiedPrice = price.map { $0 - price.min() }
- 가공한 데이터와 X축, Y축 단위로 각 포인트의 x,y 축을 구해
move(to:), addLine(to:)
메서드로 차트를 그렸습니다.
for index in simplifiedPrice.indices { let nextPoint = CGPoint( x: xUnit * Double(index) + offsetX, y: frame.size.height - (simplifiedPrice[index] * yUnit) ) context.move(to: previousPoint) context.addLine(to: nextPoint) context.closePath() previousPoint = nextPoint } context.strokePath()
- 차트 이미지 뷰로 넘어온
-
이미지 지정
image = UIGraphicsGetImageFromCurrentImageContext()?.withHorizontallyFlippedOrientation() UIGraphicsEndImageContext()
트러블 슈팅
- 스크롤 방향
상세화면 진입 시 오늘(우측)을 기준으로 과거 데이트(좌측)으로 스크롤을 이동해야했습니다.
스크롤 방향을 반대로 역전시키기 위해서 스크롤 뷰와 차트 이미지 뷰를 180도 회전 시켰습니다. 또 차트 이미지 뷰 context를 넣는 과정에서도
withHorizontallyFlippedOrientation()
메서드를 사용하여 좌우반전 시켰습니다.