### Install Dependencies Source: https://skia.org/docs/user/build Run this script to install any missing header files or other dependencies required for building Skia. ```bash tools/install_dependencies.sh ``` -------------------------------- ### Installing Clang and libfuzzer Source: https://skia.org/docs/dev/testing/fuzz Example command to install Clang version 10 and its associated development libraries, including libfuzzer, on a Debian-based system. ```bash sudo apt install clang-10 libc++-10-dev libfuzzer-10-dev ``` -------------------------------- ### Start Skia Viewer Android Activity with Arguments Source: https://skia.org/docs/user/sample/viewer Launches the Skia Viewer Android app and passes command-line arguments to it. This example starts the app with the '--androidndkfonts' argument. ```bash adb shell am start -a android.intent.action.MAIN -n org.skia.viewer/org.skia.viewer.ViewerActivity --es args '"--androidndkfonts"' ``` -------------------------------- ### Install and Run SkQP Tests Source: https://skia.org/docs/dev/testing/skqp Installs the SkQP APK and runs the tests. Ensure you replace `{APK_SHA_HERE}` with the actual commit hash of the APK. ```bash adb install -r skqp-universal-{APK_SHA_HERE}.apk adb logcat -c adb shell am instrument -w org.skia.skqp ``` -------------------------------- ### Install google-pprof Visualizer (Debian/Ubuntu) Source: https://skia.org/docs/dev/testing/profiling Installs the google-pprof analysis tool for visualizing performance profiles. Consider aliasing it to 'pprof'. ```bash # On Debian/Ubuntu: $ sudo apt-get install google-perftools ``` -------------------------------- ### Install node.js and ios-deploy Source: https://skia.org/docs/dev/testing/ios Updates Homebrew and installs the necessary Node.js environment and ios-deploy utility. ```bash $ brew update $ brew install node $ npm install ios-deploy ``` -------------------------------- ### Install LUCI client Source: https://skia.org/docs/dev/testing/download Clone the client-py repository to your local machine to access the necessary tools. ```bash git clone https://github.com/luci/client-py.git ``` -------------------------------- ### Initialize RenderEngine SKP Recording Source: https://skia.org/docs/dev/tools/android-capture Run this command once before starting RenderEngine captures to set up the recording environment. ```bash frameworks/native/libs/renderengine/skia/debug/record.sh rootandsetup ``` -------------------------------- ### Install and Run iOS App on Device Source: https://skia.org/docs/user/build Command to install and run an iOS application package on a device using ios-deploy. ```bash ios-deploy -b out/Debug/dm.app -d --args "--match foo" ``` -------------------------------- ### Install Android SDK Command Line Tools Source: https://skia.org/docs/user/sample/viewer Installs and configures the Android SDK command line tools, including setting the ANDROID_HOME environment variable. This is a prerequisite for building the Skia Viewer on Android. ```bash mkdir ~/android-sdk cd ~/android-sdk unzip ~/Downloads/commandlinetools-*.zip yes | cmdline-tools/bin/sdkmanager --licenses --sdk_root=. export ANDROID_HOME=~/android-sdk # Or wherever you installed the Android SDK. ``` -------------------------------- ### Install libimobiledevice and dependencies Source: https://skia.org/docs/dev/testing/ios Installs the core tools required for communicating with iOS devices and mounting application directories. ```bash brew install libimobiledevice brew install ideviceinstaller brew install caskroom/cask/brew-cask brew install Caskroom/cask/osxfuse brew install ifuse ``` -------------------------------- ### Configure Clang for Windows Source: https://skia.org/docs/user/build Set the LLVM installation directory for the Skia build. ```gn clang_win = "C:\Program Files\LLVM" ``` -------------------------------- ### Install gperftools for Profiling (Debian/Ubuntu) Source: https://skia.org/docs/dev/testing/profiling Installs the gperftool headers and shared libraries required for compiling and linking profiling instrumentation. ```bash # On Debian/Ubuntu: $ sudo apt-get install libgoogle-perftools-dev ``` -------------------------------- ### Setup Skia Build Environment Source: https://skia.org/docs/dev/testing/tests Commands to sync dependencies and generate build files for Skia. Ensure you have Skia's dependencies synced and the build system set up before running. ```bash python3 tools/git-sync-deps bin/gn gen out/Debug bin/gn gen out/Release --args='is_debug=false' ``` -------------------------------- ### Install depot_tools Source: https://skia.org/docs/user/download Clone the depot_tools repository and add it to your PATH. This is necessary for managing Skia's dependencies and build process. ```bash git clone 'https://chromium.googlesource.com/chromium/tools/depot_tools.git' export PATH="${PWD}/depot_tools:${PATH}" ``` -------------------------------- ### Bootstrap Styling Example Source: https://skia.org/docs/dev/tools/markdown Demonstrates using Bootstrap classes to style text elements, changing font, padding, and color without custom CSS. ```html

This is in monospace

``` -------------------------------- ### Draw Path with Multiple Contours and Styles Source: https://skia.org/docs/user/api/skpath_overview This example demonstrates drawing a path with multiple contours, including lines, quadratic curves, and conic curves. It shows how to use moveTo to start new contours and close them. The path is drawn with a stroke style. ```cpp void draw(SkCanvas* canvas) { SkPaint paint; paint.setAntiAlias(true); canvas->drawString("1st contour", 150, 100, paint); canvas->drawString("2nd contour", 130, 160, paint); canvas->drawString("3rd contour", 40, 30, paint); paint.setStyle(SkPaint::kStroke_Style); SkPath path; path.moveTo(124, 108); path.lineTo(172, 24); path.moveTo(36, 148); path.quadTo(66, 188, 120, 136); path.close(); path.conicTo(70, 20, 110, 40, 0.6f); canvas->drawPath(path, paint); } ``` -------------------------------- ### DM Test Output Example Source: https://skia.org/docs/dev/testing/testing Example of the detailed output generated by DM during a test run, showing skipped configurations and task progress. ```text Skipping nonrendering: Don't understand 'nonrendering'. Skipping angle: Don't understand 'angle'. Skipping nvprmsaa4: Could not create a surface. 492 srcs * 3 sinks + 382 tests == 1858 tasks ( 25MB 1857) 1.36ms 8888 image mandrill_132x132_12x12.astc-5-subsets ( 25MB 1856) 1.41ms 8888 image mandrill_132x132_6x6.astc-5-subsets ( 25MB 1855) 1.35ms 8888 image mandrill_132x130_6x5.astc-5-subsets ( 25MB 1854) 1.41ms 8888 image mandrill_132x130_12x10.astc-5-subsets ( 25MB 1853) 151µs 8888 image mandrill_130x132_10x6.astc-5-subsets ( 25MB 1852) 154µs 8888 image mandrill_130x130_5x5.astc-5-subsets ... ( 748MB 5) 9.43ms unit test GLInterfaceValidation ( 748MB 4) 30.3ms unit test HalfFloatTextureTest ( 748MB 3) 31.2ms unit test FloatingPointTextureTest ( 748MB 2) 32.9ms unit test DeferredCanvas_GPU ( 748MB 1) 49.4ms unit test ClipCache ( 748MB 0) 37.2ms unit test Blur ``` -------------------------------- ### Retrieve SkQP Test Report Source: https://skia.org/docs/dev/testing/skqp Pulls the SkQP test report from the device to the local machine. Replace the example output location with the actual path shown in your device logs. ```bash OUTPUT_LOCATION="/storage/emulated/0/Android/data/org.skia.skqp/files/skqp_report_2019-02-28T102058" adb pull "$OUTPUT_LOCATION" /tmp/ ``` -------------------------------- ### SkDebugf Console Log Output Example Source: https://skia.org/docs/dev/tools/tracing Example output from Skia's console logging when using the --trace debugf argument. This shows nested function calls and events. ```text [ 0] GrDrawingManager::internalFlush id=1 #0 { [ 0] } GrDrawingManager::internalFlush [ 0] GrGpu::createTexture id=1 #1 { [ 0] } GrGpu::createTexture [ 0] GrRenderTargetContext::discard id=1 #2 { [ 0] } GrRenderTargetContext::discard [ 0] SkGpuDevice::clearAll id=1 #3 { [ 1] GrRenderTargetContext::clear id=1 #4 { [ 1] } GrRenderTargetContext::clear [ 0] } SkGpuDevice::clearAll [ 0] SkCanvas::drawRect() #5 { [ 1] SkGpuDevice::drawRect id=1 #6 { [ 2] GrRenderTargetContext::drawRect id=1 #7 { [ 3] GrRenderTargetContext::addDrawOp id=1 #8 { [ 3] } GrRenderTargetContext::addDrawOp [ 2] } GrRenderTargetContext::drawRect [ 1] } SkGpuDevice::drawRect [ 0] } SkCanvas::drawRect() ... ``` -------------------------------- ### Write a Skia Benchmark Test Source: https://skia.org/docs/dev/testing/tests Example of a Skia benchmark test. This benchmark measures the performance of drawing a line. Add the file to `gn/bench.gni` and recompile. ```cpp /* * Copyright ........ * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file. */ #include "Benchmark.h" #include "SkCanvas.h" namespace { class FooBench : public Benchmark { public: FooBench() {} virtual ~FooBench() {} protected: const char* onGetName() override { return "Foo"; } SkIPoint onGetSize() override { return SkIPoint{100, 100}; } void onDraw(int loops, SkCanvas* canvas) override { while (loops-- > 0) { canvas->drawLine(0.0f, 0.0f, 100.0f, 100.0f, SkPaint()); } } }; } // namespace DEF_BENCH(return new FooBench;) ``` -------------------------------- ### Generate and Print PDF Example Source: https://skia.org/docs/user/sample/pdf This function orchestrates the creation of a PDF using the WritePDF function and then prints the resulting PDF data to standard output using the print_data utility. It defines the page size and the drawing function to be used. ```cpp void draw(SkCanvas*) { constexpr SkSize ansiLetterSize{8.5f * 72, 11.0f * 72}; SkDynamicMemoryWStream buffer; WritePDF(&buffer, "SkPDF Example", &write_page, 1, ansiLetterSize); sk_sp pdfData = buffer.detachAsData(); print_data(pdfData.get(), "skpdf_example.pdf"); } ``` -------------------------------- ### Perform various drawing operations Source: https://skia.org/docs/user/api/skcanvas_overview A comprehensive example demonstrating drawing rectangles, rounded rectangles, circles, paths, images, and text blobs. ```cpp void draw(SkCanvas* canvas) { canvas->drawColor(SK_ColorWHITE); SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(4); paint.setColor(SK_ColorRED); SkRect rect = SkRect::MakeXYWH(50, 50, 40, 60); canvas->drawRect(rect, paint); SkRRect oval; oval.setOval(rect); oval.offset(40, 60); paint.setColor(SK_ColorBLUE); canvas->drawRRect(oval, paint); paint.setColor(SK_ColorCYAN); canvas->drawCircle(180, 50, 25, paint); rect.offset(80, 0); paint.setColor(SK_ColorYELLOW); canvas->drawRoundRect(rect, 10, 10, paint); SkPath path = SkPathBuilder().cubicTo(768, 0, -512, 256, 256, 256).detach(); paint.setColor(SK_ColorGREEN); canvas->drawPath(path, paint); canvas->drawImage(image, 128, 128, SkSamplingOptions(), &paint); SkRect rect2 = SkRect::MakeXYWH(0, 0, 40, 60); canvas->drawImageRect(image, rect2, SkSamplingOptions(), &paint); SkPaint paint2; auto text = SkTextBlob::MakeFromString("Hello, Skia!", SkFont(nullptr, 18)); canvas->drawTextBlob(text.get(), 50, 25, paint2); } ``` -------------------------------- ### GN Build Arguments for ARM ChromeOS Source: https://skia.org/docs/user/build Example GN arguments for cross-compiling Skia for ARM ChromeOS devices. Ensure all paths and flags are correctly set. ```gn #ARM cc= "/opt/clang/bin/clang" cxx = "/opt/clang/bin/clang++" extra_asmflags = [ "--target=armv7a-linux-gnueabihf", "--sysroot=/opt/armhf_sysroot/", "-march=armv7-a", "-mfpu=neon", "-mthumb", ] extra_cflags=[ "--target=armv7a-linux-gnueabihf", "--sysroot=/opt/armhf_sysroot", "-I/opt/chromebook_arm_gles/include", "-I/opt/armhf_sysroot/include/", "-I/opt/armhf_sysroot/include/c++/4.8.4/", "-I/opt/armhf_sysroot/include/c++/4.8.4/arm-linux-gnueabihf/", "-DMESA_EGL_NO_X11_HEADERS", "-funwind-tables", ] extra_ldflags=[ "--sysroot=/opt/armhf_sysroot", "-B/opt/armhf_sysroot/bin", "-B/opt/armhf_sysroot/gcc-cross", "-L/opt/armhf_sysroot/gcc-cross", "-L/opt/armhf_sysroot/lib", "-L/opt/chromebook_arm_gles/lib", "--target=armv7a-linux-gnueabihf", ] target_cpu="arm" skia_use_fontconfig = false skia_use_system_freetype2 = false skia_use_egl = true ``` -------------------------------- ### Draw Path with Quad, Stroke, and Fill Styles Source: https://skia.org/docs/user/api/skpath_overview Illustrates drawing a path with a quadratic curve, applying different styles (stroke, stroke and fill) and translations. This example highlights how stroke width and fill affect the path's appearance. ```cpp void draw(SkCanvas* canvas) { SkPaint paint; paint.setAntiAlias(true); SkPath path; path.moveTo(36, 48); path.quadTo(66, 88, 120, 36); canvas->drawPath(path, paint); paint.setStyle(SkPaint::kStroke_Style); paint.setColor(SK_ColorBLUE); paint.setStrokeWidth(8); canvas->translate(0, 50); canvas->drawPath(path, paint); paint.setStyle(SkPaint::kStrokeAndFill_Style); paint.setColor(SK_ColorRED); canvas->translate(0, 50); canvas->drawPath(path, paint); } ``` -------------------------------- ### Write a Skia Rendering Test (GM) Source: https://skia.org/docs/dev/testing/tests Example of a Skia rendering test (GM). This test draws a white background and a diagonal line. Add the file to `gn/gm.gni` and recompile. ```cpp /* * Copyright ........ * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file. */ #include "gm.h" DEF_SIMPLE_GM(newgmtest, canvas, 128, 128) { canvas->clear(SK_ColorWHITE); SkPaint p; p.setStrokeWidth(2); canvas->drawLine(16, 16, 112, 112, p); } ``` -------------------------------- ### Build and Run DM Tool Source: https://skia.org/docs/dev/testing/testing Steps to synchronize dependencies, generate build files, compile the DM tool, and run a basic test. ```bash python3 tools/git-sync-deps bin/gn gen out/Debug ninja -C out/Debug dm out/Debug/dm -v -w dm_output ``` -------------------------------- ### Build Clang binaries from scratch Source: https://skia.org/docs/dev/testing/xsan Builds the Clang toolchain locally for non-Googler users. ```bash CLANGDIR="${HOME}/clang" python3 tools/git-sync-deps CC= CXX= infra/bots/assets/clang_linux/create.py -t "$CLANGDIR" ``` -------------------------------- ### Run Skia Viewer with Resource Path Source: https://skia.org/docs/user/sample/viewer Launches the Skia Viewer on desktop, specifying the path to load external resources. Replace `` with the actual path to your Skia build directory. ```bash /out/Release/viewer --resourcePath /resources ``` -------------------------------- ### Clear the canvas Source: https://skia.org/docs/user/api/skcanvas_overview Examples of clearing the canvas using either a paint object or the direct drawColor method. ```cpp void draw(SkCanvas* canvas) { SkPaint paint; paint.setColor(SK_ColorWHITE); canvas->drawPaint(paint); } ``` ```cpp void draw(SkCanvas* canvas) { canvas->drawColor(SK_ColorWHITE); } ``` -------------------------------- ### Build Skia Viewer on Desktop Source: https://skia.org/docs/user/sample/viewer Builds the Skia Viewer executable using GN and Ninja. Ensure you have the Skia build environment set up. ```bash bin/gn gen out/Release --args='is_debug=false' ninja -C out/Release viewer ``` -------------------------------- ### Create Vulkan GrContext Source: https://skia.org/docs/user/special/vulkan Initialize a Vulkan backend context and create a Skia GrContext using it. Requires a Vulkan device and queue. ```cpp skgpu::VulkanBackendContext vkContext; vkBackendContext.fInstance = vkInstance; vkBackendContext.fPhysicalDevice = vkPhysDevice; ... sk_sp context = GrDirectContexts::MakeVulkan::MakeVulkan(vkBackendContext); ``` -------------------------------- ### Build SwiftShader for Vulkan on macOS Source: https://skia.org/docs/user/special/vulkan Compile SwiftShader to enable Vulkan backend emulation on macOS. Ensure CMake is installed and in your PATH. ```bash cd $(SKIA_DIR)/third_party/externals/swiftshader/build cmake .. cmake --build . --parallel ``` -------------------------------- ### Build for Apple Silicon (M1/M2) Source: https://skia.org/docs/user/build GN arguments to set the target CPU to arm64 for building Skia on Apple Silicon Macs. ```bash bin/gn gen out/AppleSilicon --args='target_cpu="arm64"' ``` -------------------------------- ### Sync Dependencies Source: https://skia.org/docs/user/build Run this command to download and synchronize Skia's dependencies if `bin/gn` is not found. ```python python3 tools/git-sync-deps ``` -------------------------------- ### Clone Skia Buildbot Infrastructure Source: https://skia.org/docs/dev/tools/debugger Clone the Skia buildbot repository to access necessary infrastructure for building and running the debugger locally. This is a prerequisite for further setup. ```bash git clone https://skia.googlesource.com/buildbot ``` -------------------------------- ### Compose Shaders in Skia Source: https://skia.org/docs/user/api/skpaint_overview Combine two shaders using SkShaders::Blend for a compose shader effect. This example blends a radial gradient with turbulence noise. ```cpp // skpaint_compose_shader void draw(SkCanvas* canvas) { SkColor4f colors[2] = {SkColors::kBlue, SkColors::kYellow}; SkPaint paint; paint.setShader(SkShaders::Blend(SkBlendMode::kDifference, SkShaders::RadialGradient({128.0f, 128.0f}, 180.0f, {{colors, {}, SkTileMode::kClamp}, {}}), SkShaders::MakeTurbulence(0.025f, 0.025f, 2, 0.0f, nullptr))); canvas->drawPaint(paint); } ``` -------------------------------- ### Configure and compile Skia with MSAN Source: https://skia.org/docs/dev/testing/xsan Sets up the build directory and generates GN arguments for Memory Sanitizer. ```bash CLANGDIR="${HOME}/clang" mkdir -p out/msan cat > out/msan/args.gn <<- EOF cc = "${CLANGDIR}/bin/clang" cxx = "${CLANGDIR}/bin/clang++" extra_cflags = [ "-B${CLANGDIR}/bin" ] extra_ldflags = [ "-B${CLANGDIR}/bin", "-fuse-ld=lld", "-L${CLANGDIR}/msan", "-Wl,-rpath,${CLANGDIR}/msan" ] sanitize = "MSAN" skia_use_fontconfig = false EOF python3 tools/git-sync-deps bin/gn gen out/msan ninja -C out/msan ``` -------------------------------- ### Download Windows Toolchain Source: https://skia.org/docs/user/build Command to download the Windows toolchain for Skia builds. ```bash ./bin/sk.exe asset download win_toolchain C:/toolchain ``` -------------------------------- ### Configure Windows ARM64 Build Source: https://skia.org/docs/user/build Set target CPU to arm64 and enable ANGLE for graphics support. ```bash bin/gn gen out/win-arm64 --args='target_cpu="arm64" skia_use_angle=true' ``` -------------------------------- ### Draw a gradient-filled square at an offset Source: https://skia.org/docs/user/coordinates Draws a square filled with a gradient shader at position (100, 50). This example highlights that shaders do not move with geometry by default. ```cpp void draw(SkCanvas* canvas) { canvas->clear(SK_ColorGRAY); SkPaint p; SkPoint points[] = { { 0, 0 }, { 50, 0 } }; SkColor colors[] = { SK_ColorGREEN, SK_ColorBLUE }; p.setShader(SkGradientShader::MakeLinear( points, colors, nullptr, 2, SkTileMode::kClamp)); canvas->drawRect(SkRect::MakeXYWH(100, 50, 50, 50), p); } ``` -------------------------------- ### Apply Blur Mask Filter in Skia Source: https://skia.org/docs/user/api/skpaint_overview Use SkMaskFilter::MakeBlur to apply a blur effect to drawn objects. Specify the blur style and radius. This example blurs text. ```cpp void draw(SkCanvas* canvas) { canvas->drawColor(SkColorSetARGB(0xFF, 0xFF, 0xFF, 0xFF)); SkPaint paint; paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, 5.0f)); sk_sp blob = SkTextBlob::MakeFromString("Skia", SkFont(nullptr, 120)); canvas->drawTextBlob(blob.get(), 0, 160, paint); } ``` -------------------------------- ### Configure and compile Skia with ASAN Source: https://skia.org/docs/dev/testing/xsan Sets up the build directory and generates GN arguments for Address Sanitizer. ```bash CLANGDIR="${HOME}/clang" mkdir -p out/asan cat > out/asan/args.gn <<- EOF cc = "${CLANGDIR}/bin/clang" cxx = "${CLANGDIR}/bin/clang++" sanitize = "ASAN" extra_ldflags = [ "-fuse-ld=lld", "-Wl,-rpath,${CLANGDIR}/lib/x86_64-unknown-linux-gnu" ] EOF python3 tools/git-sync-deps bin/gn gen out/asan ninja -C out/asan ``` -------------------------------- ### Draw a Star Path on SkCanvas Source: https://skia.org/docs/user/api/skcanvas_creation This example function draws a five-pointed star on a given SkCanvas. It sets up a path, applies anti-aliasing, clears the canvas, and translates the origin before drawing. ```cpp #include "include/core/SkCanvas.h" #include "include/core/SkPath.h" #include "tests/Test.h" void example(SkCanvas* canvas) { const SkScalar scale = 256.0f; const SkScalar R = 0.45f * scale; const SkScalar TAU = 6.2831853f; SkPath path; for (int i = 0; i < 5; ++i) { SkScalar theta = 2 * i * TAU / 5; if (i == 0) { path.moveTo(R * cos(theta), R * sin(theta)); } else { path.lineTo(R * cos(theta), R * sin(theta)); } } path.close(); SkPaint p; p.setAntiAlias(true); canvas->clear(SK_ColorWHITE); canvas->translate(0.5f * scale, 0.5f * scale); canvas->drawPath(path, p); } DEF_TEST(FourBackends, r) { raster( 256, 256, example, "out_raster.png" ); gl_example( 256, 256, example, "out_gpu.png" ); skpdf( 256, 256, example, "out_skpdf.pdf" ); picture( 256, 256, example, "out_picture.skp"); } ``` -------------------------------- ### List Available Build Arguments Source: https://skia.org/docs/user/build View all available build arguments for a specific build directory. This helps in customizing the build process. ```bash bin/gn args out/Debug --list ``` -------------------------------- ### Generate Multiple Build Configurations Source: https://skia.org/docs/user/build Demonstrates how to create and configure multiple independent build folders for Skia, allowing for different build settings simultaneously. ```bash bin/gn gen out/Debug bin/gn gen out/Release --args='is_debug=false' bin/gn gen out/Clang --args='cc="clang" cxx="clang++"' bin/gn gen out/Cached --args='cc_wrapper="ccache"' bin/gn gen out/RTTI --args='extra_cflags_cc=["-frtti"]' ``` -------------------------------- ### Generate Multi-Configuration Visual Studio Solution Source: https://skia.org/docs/user/build Run this script after generating individual GN configurations to create a unified solution file. ```python python3 gn/gn_meta_sln.py ``` -------------------------------- ### Build for 32-bit Windows Source: https://skia.org/docs/user/build GN argument to set the target CPU to x86 for building 32-bit applications on Windows. ```gn target_cpu="x86" ``` -------------------------------- ### Create and Configure Paint Source: https://skia.org/docs/user/modules/quickstart Defines how shapes are drawn. This example creates a paint object, sets its color to red, style to stroke, enables anti-aliasing, and defines a rounded rectangle geometry. ```javascript const paint = new CanvasKit.Paint(); paint.setColor(CanvasKit.Color4f(0.9, 0, 0, 1.0)); paint.setStyle(CanvasKit.PaintStyle.Stroke); paint.setAntiAlias(true); const rr = CanvasKit.RRectXY(CanvasKit.LTRBRect(10, 60, 210, 260), 25, 15); ``` -------------------------------- ### Create and Configure SkPaint Objects Source: https://skia.org/docs/user/api/skpaint_overview Demonstrates creating multiple SkPaint objects with different color, style, and anti-aliasing settings for drawing text. Use this to define distinct visual appearances for text elements. ```cpp void draw(SkCanvas* canvas) { SkPaint paint1, paint2, paint3; paint1.setAntiAlias(true); paint1.setColor(SkColorSetRGB(255, 0, 0)); paint1.setStyle(SkPaint::kFill_Style); paint2.setAntiAlias(true); paint2.setColor(SkColorSetRGB(0, 136, 0)); paint2.setStyle(SkPaint::kStroke_Style); paint2.setStrokeWidth(SkIntToScalar(3)); paint3.setAntiAlias(true); paint3.setColor(SkColorSetRGB(136, 136, 136)); sk_sp blob1 = SkTextBlob::MakeFromString("Skia!", SkFont(nullptr, 64.0f, 1.0f, 0.0f)); sk_sp blob2 = SkTextBlob::MakeFromString("Skia!", SkFont(nullptr, 64.0f, 1.5f, 0.0f)); canvas->clear(SK_ColorWHITE); canvas->drawTextBlob(blob1.get(), 20.0f, 64.0f, paint1); canvas->drawTextBlob(blob1.get(), 20.0f, 144.0f, paint2); canvas->drawTextBlob(blob2.get(), 20.0f, 224.0f, paint3); } ``` -------------------------------- ### Fuzzing Defines for Productivity Source: https://skia.org/docs/dev/testing/fuzz These preprocessor defines can guide fuzzers to be more efficient by avoiding resource exhaustion (OOMs) or excessively slow code paths. SK_BUILD_FOR_FUZZER is enabled by default when the other two are set. ```c++ // Required for fuzzing with afl-fuzz to prevent OOMs from adding noise. SK_BUILD_FOR_AFL_FUZZ ``` ```c++ // Required for fuzzing with libfuzzer SK_BUILD_FOR_LIBFUZZER ``` ```c++ // This define adds in guards to abort when we think some code path will take a long time or // use a lot of RAM. It is set by default when either of the above defines are set. SK_BUILD_FOR_FUZZER ``` -------------------------------- ### Build Skia with Profiling Support Source: https://skia.org/docs/dev/testing/profiling Build your Skia target using ninja after enabling pprof support in args.gn. This links the CPU and heap instrumenters. ```bash $ ninja -C out/Profile nanobench ``` -------------------------------- ### SkSL Shader with Linear Lighting Example Source: https://skia.org/docs/user/sksl This SkSL shader demonstrates how to perform lighting calculations in a linear color space using `toLinearSrgb` and `fromLinearSrgb`. It compares the results with and without linear lighting. ```SkSL layout(color) uniform vec3 surfaceColor; uniform int doLinearLighting; vec3 normal_at(vec2 p) { p = (p / 128) * 2 - 1; float len2 = dot(p, p); vec3 n = (len2 > 1) ? vec3(0, 0, 1) : vec3(p, sqrt(1 - len2)); return normalize(n); } vec4 main(vec2 p) { vec3 n = normal_at(p); vec3 l = normalize(vec3(-1, -1, 0.5)); vec3 C = surfaceColor; if (doLinearLighting != 0) { C = toLinearSrgb(C); } C *= saturate(dot(n, l)); if (doLinearLighting != 0) { C = fromLinearSrgb(C); } return C.rgb1; } ``` -------------------------------- ### List Available Targets Source: https://skia.org/docs/user/build List all available build targets for a given build directory. This is useful for understanding what can be compiled. ```bash gn ls out/Debug ``` -------------------------------- ### Draw a Star Path on SkCanvas Source: https://skia.org/docs/user/sample/pdf An example function that draws a star shape onto an SkCanvas. It utilizes SkPathBuilder to define the path and SkPaint for styling. This function is intended to be used with the WritePDF function. ```cpp void write_page(SkCanvas* canvas, int) { const SkScalar R = 115.2f, C = 128.0f; SkPathBuilder path; path.moveTo(C + R, C); for (int i = 1; i < 8; ++i) { SkScalar a = 2.6927937f * i; path.lineTo(C + R * cos(a), C + R * sin(a)); } SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); canvas->drawPath(path.detach(), paint); } ``` -------------------------------- ### Build and Run DM Tool Source: https://skia.org/docs/dev/testing/testing Builds the DM tool using ninja and then runs it to write baseline images to the 'good' directory. ```bash ninja -C out/Debug dm out/Debug/dm -w good ``` -------------------------------- ### Write a Skia Unit Test Source: https://skia.org/docs/dev/testing/tests Example of a basic Skia unit test. This test checks a simple arithmetic condition and asserts a boolean value. Ensure the test file is added to `gn/tests.gni` and recompiled. ```cpp /* * Copyright ........ * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file. */ #include "Test.h" DEF_TEST(NewUnitTest, reporter) { if (1 + 1 != 2) { ERRORF(reporter, "%d + %d != %d", 1, 1, 2); } bool lifeIsGood = true; REPORTER_ASSERT(reporter, lifeIsGood); } ``` -------------------------------- ### Enable HWUI SKP Capture Source: https://skia.org/docs/dev/tools/android-capture Set the debug property to enable HWUI's SKP capture capability. This change affects applications started after the property is set, so you may need to restart the target application. ```bash adb root adb shell setprop debug.hwui.capture_skp_enabled true ``` -------------------------------- ### Enable pprof Profiling in args.gn Source: https://skia.org/docs/dev/testing/profiling Configure your Skia build to include pprof profiling support by setting `skia_use_pprof=true`. Using `-Og` is recommended for accurate line-level attribution. ```gn is_debug = false skia_use_pprof = true extra_cflags = ["-Og"] ``` -------------------------------- ### Analyze CPU Profile with pprof Annotated Source Source: https://skia.org/docs/dev/testing/profiling Examine CPU usage at the line-by-line level using `pprof -weblist`. Specify a function to focus the analysis. ```bash $ pprof -weblist ./out/Profile/nanobench # Pick a function you want to zoom in. You can run the command w/o providing # a function (or function regex), but it's quite noisy. ``` -------------------------------- ### Compile and Run Skia Benchmark Test Source: https://skia.org/docs/dev/testing/tests Commands to compile Skia and run a specific benchmark test using the nanobench tool. Use `--match` to filter benchmarks. ```bash ninja -C out/Release nanobench out/Release/nanobench --match Foo ``` -------------------------------- ### Heap Profiling with Nanobench Source: https://skia.org/docs/dev/testing/profiling Generate heap profiles using the `--memprofile` flag with nanobench. Multiple snapshots may be produced during execution. ```bash $ ./out/Profile/nanobench --match --memprofile ... Dumping heap profile to output.heap.0001.heap ... Dumping heap profile to output.heap.0002.heap ``` -------------------------------- ### Print DM Help Information Source: https://skia.org/docs/dev/testing/testing Displays all available command-line flags for the DM tool, including their default values and a brief explanation. ```bash out/Debug/dm --help ``` -------------------------------- ### Listing Supported Fuzz Types and Names Source: https://skia.org/docs/dev/testing/fuzz To understand the fuzzing capabilities, you can list all supported fuzz types and names using the `fuzz` binary with specific flags. ```bash out/ASAN/fuzz --help # will list all types ``` ```bash out/ASAN/fuzz -t api # will list all names ``` -------------------------------- ### Building Skia and Fuzzer with libfuzzer Source: https://skia.org/docs/dev/testing/fuzz Commands to build Skia and a custom fuzzer entry point using libfuzzer. This involves using ninja to build Skia and clang++ to link the fuzzer source with the Skia library. ```bash ninja -C out/libfuzzer skia ``` ```bash clang++-10 -I. -O1 -fsanitize=fuzzer fuzz/oss_fuzz/whatever.cpp out/libfuzzer/libskia.a ``` -------------------------------- ### CPU Profiling with Nanobench Source: https://skia.org/docs/dev/testing/profiling Generate a CPU profile using the `--cpuprofile` flag with nanobench. Increase the duration (`--ms`) for more comprehensive samples. ```bash $ ./out/Profile/nanobench --match --cpuprofile --ms 1000 ``` -------------------------------- ### Configure and compile Skia with TSAN Source: https://skia.org/docs/dev/testing/xsan Sets up the build directory and generates GN arguments for Thread Sanitizer. ```bash CLANGDIR="${HOME}/clang" mkdir -p out/tsan cat > out/tsan/args.gn <<- EOF cc = "${CLANGDIR}/bin/clang" cxx = "${CLANGDIR}/bin/clang++" sanitize = "TSAN" is_debug = false extra_ldflags = [ "-Wl,-rpath,${CLANGDIR}/lib" ] EOF python3 tools/git-sync-deps bin/gn gen out/tsan ninja -C out/tsan ``` -------------------------------- ### Analyze Top Functions by Flat Time with pprof Source: https://skia.org/docs/dev/testing/profiling View a list of functions with the highest 'flat' CPU time using `pprof -top`. This helps identify direct bottlenecks within functions. ```bash `$ pprof -top ./out/Profile/nanobench ` ``` -------------------------------- ### Configure Windows VC and SDK Paths Source: https://skia.org/docs/user/build GN arguments to specify the paths to the Visual C++ compiler and Windows SDK for Windows builds. ```gn win_vc = "C:\\toolchain\\VC" win_sdk = "C:\\toolchain\\win_sdk" ``` -------------------------------- ### Generate Build Files for Static Library Source: https://skia.org/docs/user/build Use this command to generate build files for Skia as a static library. Configure the build type using `--args`. ```bash bin/gn gen out/Static --args='is_official_build=true' ``` -------------------------------- ### Generate iOS Simulator Build Files (Intel) Source: https://skia.org/docs/user/build GN arguments to generate build files for the iOS simulator on Intel Macs. ```bash bin/gn gen out/iossim-intel --args='target_os="ios" target_cpu="x64"' ``` -------------------------------- ### Configure and Run Skia with ANGLE Source: https://skia.org/docs/user/special/angle Add the build argument to enable ANGLE and use the command line flags to specify the backend during execution. ```bash out/Debug/dm --src gm --config angle_d3d11_es2 out/Release/nanobench --config angle_gl_es2 ``` -------------------------------- ### Build Skia Viewer for iOS Source: https://skia.org/docs/user/sample/viewer Commands to generate build files and compile the viewer for iOS using GN and Ninja. ```bash bin/gn gen out/Release --args='target_os="ios" is_debug=false' ninja -C out/Release viewer ``` -------------------------------- ### Draw Path with MoveTo and Close Source: https://skia.org/docs/user/api/skpath_overview Demonstrates drawing a path with an initial moveTo, a quadTo, and then closing the path. The first draw call shows the path before closing, and the second shows it after closing and translating the canvas. ```cpp void draw(SkCanvas* canvas) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(8); SkPath path; path.moveTo(36, 48); path.quadTo(66, 88, 120, 36); canvas->drawPath(path, paint); path.close(); canvas->translate(0, 50); canvas->drawPath(path, paint); } ``` -------------------------------- ### Create Raster SkCanvas Source: https://skia.org/docs/user/api/skcanvas_creation Demonstrates creating a raster-backed SkCanvas where Skia manages the memory, followed by encoding the result to a PNG file. ```cpp #include "include/core/SkData.h" #include "include/core/SkImage.h" #include "include/core/SkStream.h" #include "include/core/SkSurface.h" void raster(int width, int height, void (*draw)(SkCanvas*), const char* path) { sk_sp rasterSurface = SkSurfaces::Raster(SkImageInfo::MakeN32Premul(width, height)); SkCanvas* rasterCanvas = rasterSurface->getCanvas(); draw(rasterCanvas); sk_sp img(rasterSurface->makeImageSnapshot()); if (!img) { return; } sk_sp png = SkPngEncoder::Encode(nullptr, img, {}); if (!png) { return; } SkFILEWStream out(path); (void)out.write(png->data(), png->size()); } ``` -------------------------------- ### Reproducing Fuzzes with the `fuzz` Binary Source: https://skia.org/docs/dev/testing/fuzz Use the `fuzz` binary to reproduce downloaded test cases. It can automatically detect the fuzz type and name from the testcase filename, or you can specify them manually. ```bash out/ASAN/fuzz -b /path/to/downloaded/testcase ``` ```bash out/ASAN/fuzz -t filter_fuzz -b /path/to/downloaded/testcase ``` ```bash out/ASAN/fuzz -t api -n RasterN32Canvas -b /path/to/downloaded/testcase ``` ```bash out/ASAN/fuzz -b /path/to/downloaded/testcase --loops ``` -------------------------------- ### Generate iOS Simulator Build Files (Apple Silicon) Source: https://skia.org/docs/user/build GN arguments to generate build files for the iOS simulator on Apple Silicon Macs. ```bash bin/gn gen out/iossim-apple --args='target_os="ios" target_cpu="arm64" ios_use_simulator=true' ``` -------------------------------- ### Sample an image shader in SkSL Source: https://skia.org/docs/user/sksl Demonstrates how to convert an SkImage into an SkShader and use it within an SkRuntimeEffect by calling .eval() on the shader uniform. ```cpp void draw(SkCanvas* canvas) { // Turn `image` into an SkShader: sk_sp imageShader = image->makeShader(SkSamplingOptions(SkFilterMode::kLinear)); const char* sksl = "uniform shader image;" "half4 main(float2 coord) {" " return image.eval(coord).bgra;" // Sample 'image', then swap red and blue "}"; // Parse the SkSL, and create an SkRuntimeEffect object: auto [effect, err] = SkRuntimeEffect::MakeForShader(SkString(sksl)); // SkRuntimeEffect::makeShader expects an SkSpan, one per `uniform shader`: SkRuntimeEffect::ChildPtr children[] = { imageShader }; // Create an SkShader from our SkSL, with `imageShader` bound to `image`: sk_sp myShader = effect->makeShader(/*uniforms=*/ nullptr, /*children=*/ { children, 1 }); // Fill the surface with `myShader`: SkPaint p; p.setShader(myShader); canvas->drawPaint(p); } ``` -------------------------------- ### Generate CPU Flame Graph with pprof Source: https://skia.org/docs/dev/testing/profiling Create a flame graph for CPU profiling data using `pprof -flame`. This provides an alternative visualization to the web graph. ```bash $ pprof -flame ./out/Profile/nanobench ``` -------------------------------- ### Generate 32-bit ARM iOS Build Files Source: https://skia.org/docs/user/build GN arguments to generate build files for 32-bit ARM iOS devices. ```bash bin/gn gen out/ios32 --args='target_os="ios" target_cpu="arm"' ```