1 /* 2 * Copyright 2017 Google Inc. 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 "HelloWorld.h" 9 10 #include "GrContext.h" 11 #include "SkCanvas.h" 12 #include "SkGradientShader.h" 13 #include "SkGraphics.h" 14 15 using namespace sk_app; 16 17 Application* Application::Create(int argc, char** argv, void* platformData) { 18 return new HelloWorld(argc, argv, platformData); 19 } 20 21 HelloWorld::HelloWorld(int argc, char** argv, void* platformData) 22 : fBackendType(Window::kNativeGL_BackendType) 23 , fRotationAngle(0) { 24 SkGraphics::Init(); 25 26 fWindow = Window::CreateNativeWindow(platformData); 27 fWindow->setRequestedDisplayParams(DisplayParams()); 28 29 // register callbacks 30 fWindow->pushLayer(this); 31 32 fWindow->attach(fBackendType); 33 } 34 35 HelloWorld::~HelloWorld() { 36 fWindow->detach(); 37 delete fWindow; 38 } 39 40 void HelloWorld::updateTitle() { 41 if (!fWindow || fWindow->sampleCount() <= 1) { 42 return; 43 } 44 45 SkString title("Hello World "); 46 title.append(Window::kRaster_BackendType == fBackendType ? "Raster" : "OpenGL"); 47 fWindow->setTitle(title.c_str()); 48 } 49 50 void HelloWorld::onBackendCreated() { 51 this->updateTitle(); 52 fWindow->show(); 53 fWindow->inval(); 54 } 55 56 void HelloWorld::onPaint(SkCanvas* canvas) { 57 // Clear background 58 canvas->clear(SK_ColorWHITE); 59 60 SkPaint paint; 61 paint.setColor(SK_ColorRED); 62 63 // Draw a rectangle with red paint 64 SkRect rect = SkRect::MakeXYWH(10, 10, 128, 128); 65 canvas->drawRect(rect, paint); 66 67 // Set up a linear gradient and draw a circle 68 { 69 SkPoint linearPoints[] = { { 0, 0 }, { 300, 300 } }; 70 SkColor linearColors[] = { SK_ColorGREEN, SK_ColorBLACK }; 71 paint.setShader(SkGradientShader::MakeLinear(linearPoints, linearColors, nullptr, 2, 72 SkShader::kMirror_TileMode)); 73 paint.setAntiAlias(true); 74 75 canvas->drawCircle(200, 200, 64, paint); 76 77 // Detach shader 78 paint.setShader(nullptr); 79 } 80 81 // Draw a message with a nice black paint 82 paint.setSubpixelText(true); 83 paint.setColor(SK_ColorBLACK); 84 paint.setTextSize(20); 85 86 canvas->save(); 87 static const char message[] = "Hello World"; 88 89 // Translate and rotate 90 canvas->translate(300, 300); 91 fRotationAngle += 0.2f; 92 if (fRotationAngle > 360) { 93 fRotationAngle -= 360; 94 } 95 canvas->rotate(fRotationAngle); 96 97 // Draw the text 98 canvas->drawText(message, strlen(message), 0, 0, paint); 99 100 canvas->restore(); 101 } 102 103 void HelloWorld::onIdle() { 104 // Just re-paint continously 105 fWindow->inval(); 106 } 107 108 bool HelloWorld::onChar(SkUnichar c, uint32_t modifiers) { 109 if (' ' == c) { 110 fBackendType = Window::kRaster_BackendType == fBackendType ? Window::kNativeGL_BackendType 111 : Window::kRaster_BackendType; 112 fWindow->detach(); 113 fWindow->attach(fBackendType); 114 } 115 return true; 116 } 117