SampleGlyphTransform.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 "samplecode/Sample.h"
  8. #include "tools/ToolUtils.h"
  9. #include "include/core/SkCanvas.h"
  10. #include "include/core/SkPath.h"
  11. #include "include/core/SkRRect.h"
  12. #include "include/core/SkTypeface.h"
  13. #include "include/utils/SkRandom.h"
  14. #include "tools/timer/TimeUtils.h"
  15. #include <cmath>
  16. // Implementation in C++ of Animated Emoji
  17. // See https://t.d3fc.io/status/705212795936247808
  18. // See https://crbug.com/848616
  19. class GlyphTransformView : public Sample {
  20. public:
  21. GlyphTransformView() {}
  22. protected:
  23. void onOnceBeforeDraw() override {
  24. fEmojiFont.fTypeface = ToolUtils::emoji_typeface();
  25. fEmojiFont.fText = ToolUtils::emoji_sample_text();
  26. }
  27. SkString name() override { return SkString("Glyph Transform"); }
  28. void onDrawContent(SkCanvas* canvas) override {
  29. SkPaint paint;
  30. SkFont font(fEmojiFont.fTypeface);
  31. const char* text = fEmojiFont.fText;
  32. double baseline = this->height() / 2;
  33. canvas->drawLine(0, baseline, this->width(), baseline, paint);
  34. SkMatrix ctm;
  35. ctm.setRotate(fRotate); // d3 rotate takes degrees
  36. ctm.postScale(fScale * 4, fScale * 4);
  37. ctm.postTranslate(fTranslate.fX + this->width() * 0.8, fTranslate.fY + baseline);
  38. canvas->concat(ctm);
  39. // d3 by default anchors text around the middle
  40. SkRect bounds;
  41. font.measureText(text, strlen(text), SkTextEncoding::kUTF8, &bounds);
  42. canvas->drawSimpleText(text, strlen(text), SkTextEncoding::kUTF8, -bounds.centerX(), -bounds.centerY(),
  43. font, paint);
  44. }
  45. bool onAnimate(double nanos) override {
  46. constexpr SkScalar maxt = 100000;
  47. double t = TimeUtils::PingPong(1e-9 * nanos, 20, 0, 0, maxt); // d3 t is in milliseconds
  48. fTranslate.set(sin(t / 3000) - t * this->width() * 0.7 / maxt, sin(t / 999) / t);
  49. fScale = 4.5 - std::sqrt(t) / 99;
  50. fRotate = sin(t / 734);
  51. return true;
  52. }
  53. private:
  54. struct EmojiFont {
  55. sk_sp<SkTypeface> fTypeface;
  56. const char* fText;
  57. } fEmojiFont;
  58. SkVector fTranslate;
  59. SkScalar fScale;
  60. SkScalar fRotate;
  61. typedef Sample INHERITED;
  62. };
  63. //////////////////////////////////////////////////////////////////////////////
  64. DEF_SAMPLE( return new GlyphTransformView(); )