Home > Enterprise >  Trim Shape() horizontally with Swiftui
Trim Shape() horizontally with Swiftui

Time:07-22

Trim by Swiftui allowed me to make a circle filled with 2 different colors. The problem i'm facing now is i want to trim my circles from horizontally but the trim only work vertically. I tried using hstack to help this process but it did not work.

Is there any solution to fix this problem?
enter image description here

ZStack {
        //HStack get removed from here
        Circle()
            .trim(from: 0.5, to: 1)
            .fill(.blue)
        Circle()
            .trim(from: 0, to: 0.5)
            .fill(.red)
        Circle()
            .strokeBorder(lineWidth: 24)
       }

CodePudding user response:

The simplest is just to rotate entire view (ZStack in this case)

ZStack {
   // ... same code here
}.rotationEffect(.radians(.pi/2))

demo

CodePudding user response:

For your information, HStack is not the case here.

To achieve your desired design, just rotate your Circle() after it is trimmed.

Try this code below:

 ZStack {
      Circle()
            .trim(from: 0.5, to: 1)
            .fill(.blue)
            .rotationEffect(.degrees(90))
      Circle()
            .trim(from: 0, to: 0.5)
            .fill(.red)
            .rotationEffect(.degrees(90))
      Circle()
            .strokeBorder(lineWidth: 24)
 }

CodePudding user response:

Here is a way to do it without rotating. Start with a red circle and cover it with a half blue circle trimmed from 0.25 to 0.75:

ZStack {
    Circle()
        .fill(.red)
    Circle()
        .trim(from: 0.25, to: 0.75)
        .fill(.blue)
    Circle()
        .strokeBorder(lineWidth: 24)
}

circle drawn with 2 colors

  • Related