xref: /aosp_15_r20/external/skia/docs/examples/Canvas_accessTopLayerPixels_b.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 // Copyright 2019 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 REG_FIDDLE(Canvas_accessTopLayerPixels_b, 256, 256, false, 0) {
draw(SkCanvas * canvas)5 void draw(SkCanvas* canvas) {
6   SkPaint paint;
7   SkFont font(fontMgr->matchFamilyStyle(nullptr, {}), 100);
8   canvas->drawString("ABC", 20, 160, font, paint);
9   SkRect layerBounds = SkRect::MakeXYWH(32, 32, 192, 192);
10   canvas->saveLayerAlpha(&layerBounds, 128);
11   canvas->clear(SK_ColorWHITE);
12   canvas->drawString("DEF", 20, 160, font, paint);
13   SkImageInfo imageInfo;
14   size_t rowBytes;
15   SkIPoint origin;
16   uint32_t* access = (uint32_t*) canvas->accessTopLayerPixels(&imageInfo, &rowBytes, &origin);
17   if (access) {
18     int h = imageInfo.height();
19     int v = imageInfo.width();
20     int rowWords = rowBytes / sizeof(uint32_t);
21     for (int y = 0; y < h; ++y) {
22         int newY = (y - h / 2) * 2 + h / 2;
23         if (newY < 0 || newY >= h) {
24             continue;
25         }
26         for (int x = 0; x < v; ++x) {
27             int newX = (x - v / 2) * 2 + v / 2;
28             if (newX < 0 || newX >= v) {
29                 continue;
30             }
31             if (access[y * rowWords + x] == SK_ColorBLACK) {
32                 access[newY * rowWords + newX] = SK_ColorGRAY;
33             }
34         }
35     }
36   }
37   canvas->restore();
38 }
39 }  // END FIDDLE
40