1 /* 2 * Copyright 2018 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 #include "Sample.h" 8 #include "sk_tool_utils.h" 9 10 #include "SkAnimTimer.h" 11 #include "SkCanvas.h" 12 #include "SkPath.h" 13 #include "SkRandom.h" 14 #include "SkRRect.h" 15 #include "SkTypeface.h" 16 17 #include <cmath> 18 19 // Implementation in C++ of Animated Emoji 20 // See https://t.d3fc.io/status/705212795936247808 21 // See https://crbug.com/848616 22 23 class GlyphTransformView : public Sample { 24 public: GlyphTransformView()25 GlyphTransformView() {} 26 27 protected: onOnceBeforeDraw()28 void onOnceBeforeDraw() override { 29 fEmojiFont.fTypeface = sk_tool_utils::emoji_typeface(); 30 fEmojiFont.fText = sk_tool_utils::emoji_sample_text(); 31 } 32 onQuery(Sample::Event * evt)33 bool onQuery(Sample::Event* evt) override { 34 if (Sample::TitleQ(*evt)) { 35 Sample::TitleR(evt, "Glyph Transform"); 36 return true; 37 } 38 return this->INHERITED::onQuery(evt); 39 } 40 onDrawContent(SkCanvas * canvas)41 void onDrawContent(SkCanvas* canvas) override { 42 SkPaint paint; 43 44 SkFont font(fEmojiFont.fTypeface); 45 const char* text = fEmojiFont.fText; 46 47 double baseline = this->height() / 2; 48 canvas->drawLine(0, baseline, this->width(), baseline, paint); 49 50 SkMatrix ctm; 51 ctm.setRotate(fRotate); // d3 rotate takes degrees 52 ctm.postScale(fScale * 4, fScale * 4); 53 ctm.postTranslate(fTranslate.fX + this->width() * 0.8, fTranslate.fY + baseline); 54 canvas->concat(ctm); 55 56 // d3 by default anchors text around the middle 57 SkRect bounds; 58 font.measureText(text, strlen(text), kUTF8_SkTextEncoding, &bounds); 59 canvas->drawSimpleText(text, strlen(text), kUTF8_SkTextEncoding, -bounds.centerX(), -bounds.centerY(), 60 font, paint); 61 } 62 onAnimate(const SkAnimTimer & timer)63 bool onAnimate(const SkAnimTimer& timer) override { 64 constexpr SkScalar maxt = 100000; 65 double t = timer.pingPong(20, 0, 0, maxt); // d3 t is in milliseconds 66 67 fTranslate.set(sin(t / 3000) - t * this->width() * 0.7 / maxt, sin(t / 999) / t); 68 fScale = 4.5 - std::sqrt(t) / 99; 69 fRotate = sin(t / 734); 70 71 return true; 72 } 73 74 private: 75 struct EmojiFont { 76 sk_sp<SkTypeface> fTypeface; 77 const char* fText; 78 } fEmojiFont; 79 80 SkVector fTranslate; 81 SkScalar fScale; 82 SkScalar fRotate; 83 84 typedef Sample INHERITED; 85 }; 86 87 ////////////////////////////////////////////////////////////////////////////// 88 89 DEF_SAMPLE( return new GlyphTransformView(); ) 90