xref: /aosp_15_r20/external/skia/docs/examples/Bitmap_tryAllocPixels_4.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(Bitmap_tryAllocPixels_4, 256, 100, false, 0) {
5 class LargePixelRef : public SkPixelRef {
6 public:
LargePixelRef(const SkImageInfo & info,char * storage,size_t rowBytes)7     LargePixelRef(const SkImageInfo& info, char* storage, size_t rowBytes)
8         : SkPixelRef(info.width(), info.height(), storage, rowBytes) {
9     }
~LargePixelRef()10     ~LargePixelRef() override {
11         delete[] (char* ) this->pixels();
12     }
13 };
14 class LargeAllocator : public SkBitmap::Allocator {
15 public:
allocPixelRef(SkBitmap * bitmap)16     bool allocPixelRef(SkBitmap* bitmap) override {
17         const SkImageInfo& info = bitmap->info();
18         uint64_t rowBytes = info.minRowBytes64();
19         uint64_t size = info.height() * rowBytes;
20         char* addr = new char[size];
21         if (nullptr == addr) {
22             return false;
23         }
24         sk_sp<SkPixelRef> pr = sk_sp<SkPixelRef>(new LargePixelRef(info, addr, rowBytes));
25         if (!pr) {
26             return false;
27         }
28         bitmap->setPixelRef(std::move(pr), 0, 0);
29         return true;
30     }
31 };
32 
draw(SkCanvas * canvas)33 void draw(SkCanvas* canvas) {
34    LargeAllocator largeAllocator;
35    SkBitmap bitmap;
36    int width = 100; // make this 20000
37    int height = 100; // and this 100000 to allocate 8 gigs on a 64-bit platform
38    bitmap.setInfo(SkImageInfo::MakeN32(width, height, kOpaque_SkAlphaType));
39    if (bitmap.tryAllocPixels(&largeAllocator)) {
40        bitmap.eraseColor(0xff55aa33);
41        canvas->drawImage(bitmap.asImage(), 0, 0);
42    }
43 }
44 }  // END FIDDLE
45