| 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(Picture_MakeFromData, 256, 256, false, 0) { |
| 5 |
void draw(SkCanvas* canvas) { |
| 6 |
SkPictureRecorder recorder; |
| 7 |
SkCanvas* pictureCanvas = recorder.beginRecording({0, 0, 256, 256}); |
| 8 |
SkPaint paint; |
| 9 |
pictureCanvas->drawRect(SkRect::MakeWH(200, 200), paint); |
| 10 |
paint.setColor(SK_ColorWHITE); |
| 11 |
pictureCanvas->drawRect(SkRect::MakeLTRB(20, 20, 180, 180), paint); |
| 12 |
sk_sp<SkPicture> picture = recorder.finishRecordingAsPicture(); |
| 13 |
SkDynamicMemoryWStream writableStream; |
| 14 |
|
| 15 |
// The above drawing doesn't have any images to serialize, but if such |
| 16 |
// serialization were necessary, one would need to register an encoder. |
| 17 |
SkSerialProcs sProcs; |
| 18 |
sProcs.fImageProc = [](SkImage* img, void*) -> SkSerialReturnType { |
| 19 |
#if defined(SK_CODEC_ENCODES_PNG_WITH_RUST) |
| 20 |
return SkPngRustEncoder::Encode(nullptr, img, SkPngRustEncoder::Options{}); |
| 21 |
#else |
| 22 |
return SkPngEncoder::Encode(nullptr, img, SkPngEncoder::Options{}); |
| 23 |
#endif |
| 24 |
}; |
| 25 |
picture->serialize(&writableStream, &sProcs); |
| 26 |
|
| 27 |
sk_sp<SkData> readableData = writableStream.detachAsData(); |
| 28 |
|
| 29 |
SkDeserialProcs dProcs; |
| 30 |
// The above SKP doesn't have any image data in it, but if it did, a decoder |
| 31 |
// needs to be registered like this. |
| 32 |
dProcs.fImageDataProc = |
| 33 |
[](sk_sp<SkData> data, std::optional<SkAlphaType> at, void*) -> sk_sp<SkImage> { |
| 34 |
#if defined(SK_CODEC_DECODES_PNG_WITH_RUST) |
| 35 |
std::unique_ptr<SkStream> stream = SkMemoryStream::Make(std::move(data)); |
| 36 |
auto codec = SkPngRustDecoder::Decode(std::move(stream), nullptr, nullptr); |
| 37 |
#else |
| 38 |
auto codec = SkPngDecoder::Decode(std::move(data), nullptr, nullptr); |
| 39 |
#endif |
| 40 |
if (!codec) { |
| 41 |
SkDebugf("Invalid png data detected\n"); |
| 42 |
return nullptr; |
| 43 |
} |
| 44 |
if (auto lazyImage = SkCodecs::DeferredImage(std::move(codec), at)) { |
| 45 |
return lazyImage->makeRasterImage(/*GrDirectContext=*/nullptr); |
| 46 |
} |
| 47 |
return nullptr; |
| 48 |
}; |
| 49 |
sk_sp<SkPicture> copy = SkPicture::MakeFromData(readableData.get(), &dProcs); |
| 50 |
copy->playback(canvas); |
| 51 |
} |
| 52 |
} // END FIDDLE |