İçeriğe geç

SwiftUI ile Custom Path oluşturmak

Merhabalar bu yazımda SwiftUI ile birlikte custom bir shape sınıfı kullanarak grafik çizme veya farklı nesneler yaratma işlemini nasıl gerçekleştirebileceğinizi sizlerle paylaşacağım.

Bir önceki yazımda giriş yaptığım Path ile çizim işlemine bugün göstereceğim örnektede devam edeceğiz. Custom geometrik nesneler veya grafikler çizmek için oluşturacağınız struct yapısına Shape protokolünü ekliyoruz. Daha sonrasında oluşturduğumuz struct içerisinde path(in rect: CGRect) fonksiyon bloğu içerisine gerekli çizim kodlarımızı yazabiliriz.

struct CustomGraph: Shape {
    
    var dataPoints: [CGFloat]
    
    func path(in rect: CGRect) -> Path {
        func point(at ix: Int) -> CGPoint {
            let point = dataPoints[ix]
            let x = rect.width * CGFloat(ix) / CGFloat(dataPoints.count - 1)
            let y = (1 - point) * rect.height
            return CGPoint(x: x, y: y)
        }
        
        return Path { p in
            guard dataPoints.count > 1 else { return }
            let start = dataPoints[0]
            p.move(to: CGPoint(x: 0, y: (1 - start) * rect.height))
            for idx in dataPoints.indices {
                p.addLine(to: point(at: idx))
            }
        }
    }
}
struct ContentView: View {
    
    @State var on = false
    
    var body: some View {
        VStack {
            CustomGraph(dataPoints: [0, 0.10 ,0.12 ,0.23 ,0.19 ,0.45 , 0.66, 0.70, 0.85, 1])
                .trim(to: on ? 1 : 0)
                .stroke(Color.red, lineWidth: 2)
                .aspectRatio(16/9, contentMode: .fit)
                .border(Color.gray, width: 1)
                .padding()
                .onAppear(perform: {
                    withAnimation(.easeInOut(duration: 1.5)) {
                        self.on = true
                    }
                })
        }
    }
}

 

 

Kategori:SwiftUI

İlk Yorumu Siz Yapın

Bir cevap yazın

E-posta hesabınız yayımlanmayacak.

Copyright © 2022 Kenan Atmaca