Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a moon shape?

Tags:

swiftui

I would like to create a moon shape. Currently, I achieved it by placing another circle on top and then giving it the same colour as the background colour.

Perhaps using a clipped shape or masking layer.

I was wondering if there's a better way to do this?

ZStack{
    Circle().foregroundColor(isDarkMode ? Color( colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)) : Color.yellow)
        .frame(width: 30, height: 30)
        .offset(x: isDarkMode ? 20 : -20)
    
    Circle().foregroundColor(isDarkMode ? Color( colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1)) : Color.white)
        .frame(width: 30, height: 30)
        .offset(x: isDarkMode ? 6 : -20).rotationEffect(.degrees( isDarkMode ? -40 : 0)) 
}
like image 401
test testing Avatar asked Nov 28 '25 11:11

test testing


1 Answers

Here is a demo of possible approach. Tested with Xcode 12 / iOS 14.

demo

struct MoonMask: Shape {
    func path(in rect: CGRect) -> Path {
        var path = Rectangle().path(in: rect)
        path.addPath(Circle().path(in: rect.inset(by: UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 10))
            .offsetBy(dx: 50, dy: -10)))
        return path
    }
}

struct MoonView: View {
    var body: some View {

        Circle()
            .mask(MoonMask().fill(style: FillStyle(eoFill: true)))

            // below is just demo
            .frame(width: 200, height: 200)
            .foregroundColor(Color.yellow)
            .padding().background(Color.black)
    }
}
like image 117
Asperi Avatar answered Nov 30 '25 04:11

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!