xref: /aosp_15_r20/external/skia/example/external_client/src/write_text_to_png.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2023 Google LLC
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "include/core/SkAlphaType.h"
9 #include "include/core/SkCanvas.h"
10 #include "include/core/SkColor.h"
11 #include "include/core/SkImageInfo.h"
12 #include "include/core/SkRefCnt.h"
13 #include "include/core/SkTypeface.h"
14 #include "include/core/SkFont.h"
15 #include "include/core/SkFontStyle.h"
16 #include "include/core/SkFontMgr.h"
17 #include "include/core/SkPixmap.h"
18 #include "include/core/SkSurface.h"
19 #include "include/core/SkStream.h"
20 #include "include/encode/SkPngEncoder.h"
21 
22 #if defined(SK_FONTMGR_FONTCONFIG_AVAILABLE)
23 #include "include/ports/SkFontMgr_fontconfig.h"
24 #include "include/ports/SkFontScanner_FreeType.h"
25 #endif
26 
27 #if defined(SK_FONTMGR_CORETEXT_AVAILABLE)
28 #include "include/ports/SkFontMgr_mac_ct.h"
29 #endif
30 
31 #include <cstdio>
32 
main(int argc,char ** argv)33 int main(int argc, char** argv) {
34     if (argc != 2) {
35         printf("Usage: %s <name.png>", argv[0]);
36         return 1;
37     }
38     SkFILEWStream output(argv[1]);
39     if (!output.isValid()) {
40         printf("Cannot open output file %s\n", argv[1]);
41         return 1;
42     }
43     sk_sp<SkSurface> surface = SkSurfaces::Raster(SkImageInfo::MakeN32(100, 50, kOpaque_SkAlphaType));
44     SkCanvas* canvas = surface->getCanvas();
45 #if defined(SK_FONTMGR_FONTCONFIG_AVAILABLE)
46     sk_sp<SkFontMgr> mgr = SkFontMgr_New_FontConfig(nullptr, SkFontScanner_Make_FreeType());
47 #endif
48 #if defined(SK_FONTMGR_CORETEXT_AVAILABLE)
49     sk_sp<SkFontMgr> mgr = SkFontMgr_New_CoreText(nullptr);
50 #endif
51 
52     sk_sp<SkTypeface> face = mgr->matchFamilyStyle("Roboto", SkFontStyle());
53     if (!face) {
54       printf("Cannot open typeface\n");
55       return 1;
56     }
57     SkFont font(face, 14);
58     SkPaint paint;
59     paint.setColor(SK_ColorGREEN);
60     canvas->clear(SK_ColorYELLOW);
61     canvas->drawString("Hello world!", 10, 25, font, paint);
62     SkPixmap pixmap;
63     if (surface->peekPixels(&pixmap)) {
64         if (!SkPngEncoder::Encode(&output, pixmap, {})) {
65           printf("Cannot write output\n");
66           return 1;
67         }
68     } else {
69       printf("Cannot readback on surface\n");
70       return 1;
71     }
72     return 0;
73 }
74