-1

In My example, I draw a rect use GraphicsContext.

Canvas { context, size in
    context.fill(
        Path(CGRect(
            x: 0,
            y: 0,
            width: 300,
            height: 200
        )),
        with: .color(.green))
}
.frame(width: 300, height: 200)

Now, I want clear the rect, but not found the clear api in GraphicsContext, how clear the rect?

I try to fill another Color.clear rect overlap the green rect, but not clear rect.

context.fill(
    Path(CGRect(
        x: 0,
        y: 0,
        width: 300,
        height: 200
    )),
    with: .color(.clear))

1 Answers1

2

You can use blendMode to copy the color you are trying to apply. See the following code:

context.blendMode = .copy
context.fill(
    Path(CGRect(
        x: 0,
        y: 0,
        width: 300,
        height: 200
    )),
    with: .color(.clear))
context.blendMode = .normal

We first set the blend mode to copy so that the oncoming color is copied directly to context without doing any computations. We then need to reset the blend mode back to normal.

This seems to work correctly at least for my test case. But you are absolutely right. There are chunks of API missing. What I am personally missing for this case is actually saveGState and restoreGState. These can push-pop your settings on context so that when you restore it you know you have restored settings to what was previously set. Now in our code we just assume that we need to revert blend mode back to .normal.

Matic Oblak
  • 16,318
  • 3
  • 24
  • 43
  • Set `context.blendMode = .copy` is work, I trying replace `.copy` to `.clear` still work, I think `.clear` better `.copy` for clear the rect after read docs, not sure if my understanding is right, but still thanks The `saveGState` and `restoreGState` is missing, I use a queue store the context state, the GraphicsContext should provide these basic API like HTML Canvas. – 雨夜带刀 May 02 '23 at 01:46
  • @雨夜带刀 The difference is documented as `R = S` for copy and `R = 0` for clear. I am half-guessing that this translates to "Result equals to Source" and "Result equals to Zero". So use `copy` when you want to control which color you want to forcefully apply or clear to. And use `clear` if you are fine with filling it with all zeros (which is also a clear color). – Matic Oblak May 02 '23 at 19:24
  • Professional – 雨夜带刀 May 03 '23 at 08:24