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 "include/core/SkTypes.h" 9 10 #ifdef SK_XML 11 12 #include "include/core/SkCanvas.h" 13 #include "include/core/SkRect.h" 14 #include "include/core/SkStream.h" 15 #include "modules/svg/include/SkSVGDOM.h" 16 #include "samplecode/Sample.h" 17 #include "src/core/SkOSFile.h" 18 #include "src/utils/SkOSPath.h" 19 #include "src/xml/SkDOM.h" 20 #include "tools/Resources.h" 21 22 namespace { 23 class AnimatedSVGSample : public Sample { 24 static constexpr auto kAnimationIterations = 5; 25 enum State { 26 kZoomIn, 27 kScroll, 28 kZoomOut 29 }; 30 sk_sp<SkSVGDOM> fDom; 31 const char* fResource = nullptr; 32 const char* fName = nullptr; 33 State fState = kZoomIn; 34 int fAnimationLoop = kAnimationIterations; 35 SkScalar fDelta = 1; 36 37 public: AnimatedSVGSample(const char * r,const char * n)38 AnimatedSVGSample(const char* r, const char* n) : fResource(r), fName(n) {} 39 40 private: onOnceBeforeDraw()41 void onOnceBeforeDraw() override { 42 SkASSERT(fResource); 43 auto data = GetResourceAsData(fResource); 44 if (!data) { 45 SkDebugf("Resource not found: \"%s\"\n", fResource); 46 return; 47 } 48 SkMemoryStream svgStream(std::move(data)); 49 50 fDom = SkSVGDOM::MakeFromStream(svgStream); 51 if (fDom) { 52 fDom->setContainerSize(SkSize::Make(this->width(), this->height())); 53 } 54 } 55 onDrawContent(SkCanvas * canvas)56 void onDrawContent(SkCanvas* canvas) override { 57 if (fDom) { 58 canvas->setMatrix(SkMatrix::Scale(3, 3)); 59 canvas->clipRect(SkRect::MakeLTRB(0, 0, 400, 400)); 60 switch (fState) { 61 case kZoomIn: 62 fDelta += 0.2f; 63 canvas->scale(fDelta, fDelta); 64 break; 65 case kScroll: 66 if (fAnimationLoop > kAnimationIterations/2) { 67 fDelta += 80.f; 68 } else { 69 fDelta -= 80.f; 70 } 71 canvas->scale(fDelta, fDelta); 72 canvas->translate(fDelta, 0); 73 break; 74 case kZoomOut: 75 fDelta += 0.2f; 76 canvas->scale(fDelta, fDelta); 77 break; 78 } 79 80 fDom->render(canvas); 81 } 82 } 83 onSizeChange()84 void onSizeChange() override { 85 if (fDom) { 86 fDom->setContainerSize(SkSize::Make(this->width(), this->height())); 87 } 88 } 89 name()90 SkString name() override { return SkASSERT(fName), SkString(fName); } 91 onAnimate(double nanos)92 bool onAnimate(double nanos) override { 93 if (!fDom) { 94 return false; 95 } 96 97 --fAnimationLoop; 98 if (fAnimationLoop == 0) { 99 fAnimationLoop = kAnimationIterations; 100 switch (fState) { 101 case kZoomIn: 102 fState = kScroll; 103 fDelta = 0; 104 break; 105 case kScroll: 106 fState = kZoomOut; 107 fDelta = 2; 108 break; 109 case kZoomOut: 110 fState = kZoomIn; 111 fDelta = 1; 112 break; 113 } 114 } 115 return true; 116 } 117 }; 118 } // namespace 119 120 DEF_SAMPLE( return new AnimatedSVGSample("Cowboy.svg", "SampleCowboy"); ) 121 122 #endif // SK_XML 123