Home > Software design >  SwiftUI - Creating a Star Rating View with decimal point fillable foreground colour in
SwiftUI - Creating a Star Rating View with decimal point fillable foreground colour in

Time:12-06

I am trying to develop a star rating view using SwiftUI. I have a maximum of 5 stars, and the tricky part is that I need to fill 4.7 stars. So the last star should only fill up 70% of its foreground color.

Below is the code that I have done so far

import SwiftUI
 
struct AverageStarsView: View {
    @Binding var rating: Double
    
    var body: some View {
        Group {
            StarView()
        }
        .frame(maxHeight: 16)
    }
}
 
struct AverageStarsView_Previews: PreviewProvider {
    static var previews: some View {
        AverageStarsView(rating: .constant(4.7))
    }
}
struct StarView: View {
    private var fillColor = .yellow
    private var emptyColor = .grey
 
    var body: some View {
        ZStack {
            if let starImage =  UIImage(named: "icon-star", in: .sharedResources, compatibleWith: nil) {
                Image(uiImage: starImage)
                    .resizable()
                    .renderingMode(.template)
                    .foregroundColor(emptyColor)                    
                    .aspectRatio(contentMode: .fit)
            }
        }
    }
    
}
 
struct StarView_Previews: PreviewProvider {
    static var previews: some View {
        StarView()
    }
}

How can fill only 70% of the star view. I can't use .overlay because I need to support iOS 14.

enter image description here

You can then stack them into an HStack and make a quick calculation to know the fill value of the last star to make your five stars rating component.

Make sure to use .mask() and not .mask { } as the last one require iOS 15.0 to be used.

  • Related