AndiAna
AndiAna

Reputation: 964

How can I clip a Shape with another Shape in SwiftUI?

I want to clip the red square with the green half-circle. I tried .mask and .clipShape but i can't get this to work. Can someone share how its done please?

import SwiftUI

struct TestEndBarView: View {
    var body: some View {
        ZStack {
                Rectangle()
                    .fill(Color.red)
                    .frame(width: 500, height: 500)
                Circle()
                    .trim(from: 0.5, to: 1.0)
                    .fill(Color.green)
                    .rotationEffect(Angle(degrees: 90))
                    .frame(width: 500, height: 500)
                    .offset(x: -250)
                    
        }
    }
}

struct TestEndBarView_Previews: PreviewProvider {
    static var previews: some View {
        TestEndBarView()
    }
}

A red square with a green half circle

Upvotes: 2

Views: 2383

Answers (3)

AndiAna
AndiAna

Reputation: 964

My code is this basic one. Maybe someone finds this useful so i am attaching it here as well.

import SwiftUI

struct TestEndBarView: View {
    var body: some View {
        ZStack {
            BoxCutOut()
                .foregroundColor(Color.red)
                    
        }
    }
}

struct TestEndBarView_Previews: PreviewProvider {
    static var previews: some View {
        TestEndBarView()
    }
}

struct BoxCutOut: Shape {
    func path(in rect: CGRect) -> Path {
        Path { path in
            path.move(to: CGPoint(x:0, y: 0))
            path.addLine(to: CGPoint(x:rect.width, y:0))
            path.addLine(to: CGPoint(x:rect.width, y:rect.height))
            path.addLine(to: CGPoint(x:0, y:rect.height))
            path.addArc(center: CGPoint(x: 0, y: rect.height/2), radius: rect.height/2, startAngle: .degrees(90), endAngle: .degrees(270), clockwise: true )
        }
    }
}

Upvotes: 0

swiftPunk
swiftPunk

Reputation: 1

with using eoFill like in the code:


enter image description here


struct ContentView: View {

    var body: some View {
        
        CustomShape()
            .fill(Color.purple, style: FillStyle(eoFill: true, antialiased: true))
            .frame(width: 200, height: 200, alignment: .center)
            .shadow(radius: 10.0)
 
    }
}

struct CustomShape: Shape {
    
    func path(in rect: CGRect) -> Path {
        
        return Path { path in
            path.addArc(center: CGPoint(x: rect.minX, y: rect.midY), radius: rect.height/2, startAngle: Angle(degrees: 90), endAngle: Angle(degrees: 270), clockwise: true)
            path.addRect(CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: rect.height))
 
        }
        
    }
}

Upvotes: 3

EmilioPelaez
EmilioPelaez

Reputation: 19882

Create a struct that conforms to Shape.

Implement func path(in rect: CGRect) -> Path

Create a Path. Add the rectangle, then the circle.

Fill the shape with isEOFilled set to true

Upvotes: 2

Related Questions