1// Copyright 2020 Google LLC. 2// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. 3#include "tools/fiddle/examples.h" 4// HASH=7d3751e82d1b6ec328ffa3d6f48ca831 5REG_FIDDLE(Canvas_saveLayer_4, 256, 256, false, 3) { 6void draw(SkCanvas* canvas) { 7 SkPaint pRed; 8 pRed.setColor(SK_ColorRED); 9 10 SkPaint pSolidBlue; 11 pSolidBlue.setColor(SK_ColorBLUE); 12 13 SkPaint pThirtyBlue; 14 pThirtyBlue.setColor(SK_ColorBLUE); 15 pThirtyBlue.setAlphaf(0.3); 16 17 SkPaint alpha; 18 alpha.setAlphaf(0.3); 19 20 // First row: Draw two opaque red rectangles into the 0th layer. Then draw two blue 21 // rectangles overlapping the red, one is solid, the other is 30% transparent. 22 canvas->drawRect(SkRect::MakeLTRB(10, 10, 60, 60), pRed); 23 canvas->drawRect(SkRect::MakeLTRB(150, 10, 200, 60), pRed); 24 25 canvas->drawRect(SkRect::MakeLTRB(30, 10, 80, 60), pSolidBlue); 26 canvas->drawRect(SkRect::MakeLTRB(170, 10, 220, 60), pThirtyBlue); 27 28 // Second row: Draw two opaque red rectangles into the 0th layer. Then save a new layer; 29 // when the 1st layer gets merged onto the 0th layer (i.e. when restore() is called), it will 30 // use the provided paint to do so. In this case, the paint is set to have 30% opacity, but 31 // it could also have things set like blend modes or image filters. 32 canvas->drawRect(SkRect::MakeLTRB(10, 70, 60, 120), pRed); 33 canvas->drawRect(SkRect::MakeLTRB(150, 70, 200, 120), pRed); 34 35 canvas->saveLayer(nullptr, &alpha); 36 37 // In the 1st layer, draw the same blue overlapping rectangles as in the first row. Notice in 38 // the final output, we have two different shades of purple. The layer's alpha made the 39 // opaque blue rectangle transparent, and it made the transparent blue rectangle even more so 40 canvas->drawRect(SkRect::MakeLTRB(30, 70, 80, 120), pSolidBlue); 41 canvas->drawRect(SkRect::MakeLTRB(170, 70, 220, 120), pThirtyBlue); 42 43 canvas->restore(); 44 45 // Third row: save the layer first, before drawing the two red rectangle, followed by the 46 // overlapping blue rectangles. Notice that the blue overwrites the red in the same way as 47 // the first row because the alpha of the layer is not applied until the layer is restored. 48 canvas->saveLayer(nullptr, &alpha); 49 50 canvas->drawRect(SkRect::MakeLTRB(10, 130, 60, 180), pRed); 51 canvas->drawRect(SkRect::MakeLTRB(150, 130, 200, 180), pRed); 52 53 canvas->drawRect(SkRect::MakeLTRB(30, 130, 80, 180), pSolidBlue); 54 canvas->drawRect(SkRect::MakeLTRB(170, 130, 220, 180), pThirtyBlue); 55 56 canvas->restore(); 57} 58} // END FIDDLE 59