| 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 |
|
| 8 |
#include "include/core/SkCanvas.h" |
| 9 |
#include "include/core/SkData.h" |
| 10 |
#include "include/core/SkImage.h" |
| 11 |
#include "modules/skresources/include/SkResources.h" |
| 12 |
#include "tools/Resources.h" |
| 13 |
#include "tools/viewer/AnimatedImageSlide.h" |
| 14 |
#include <cmath> |
| 15 |
|
| 16 |
AnimatedImageSlide::AnimatedImageSlide(const SkString& name, const SkString& path) |
| 17 |
: fPath(path) |
| 18 |
{ |
| 19 |
fName = name; |
| 20 |
} |
| 21 |
|
| 22 |
void AnimatedImageSlide::load(SkScalar w, SkScalar h) { |
| 23 |
fWinSize = {w, h}; |
| 24 |
|
| 25 |
// Try loading both as a resource and as a regular file. |
| 26 |
sk_sp<SkData> data = GetResourceAsData(fPath.c_str()); |
| 27 |
if (!data) { |
| 28 |
data = SkData::MakeFromFileName(fPath.c_str()); |
| 29 |
} |
| 30 |
|
| 31 |
fImageAsset = skresources::MultiFrameImageAsset::Make(std::move(data)); |
| 32 |
} |
| 33 |
|
| 34 |
void AnimatedImageSlide::unload() { |
| 35 |
fImageAsset.reset(); |
| 36 |
fTimeBase = 0; |
| 37 |
} |
| 38 |
|
| 39 |
void AnimatedImageSlide::draw(SkCanvas* canvas) { |
| 40 |
if (!fImageAsset) { |
| 41 |
return; |
| 42 |
} |
| 43 |
|
| 44 |
sk_sp<SkImage> frame = fImageAsset->getFrame(fFrameMs * 0.001f); |
| 45 |
|
| 46 |
SkAutoCanvasRestore acr(canvas, true); |
| 47 |
canvas->translate((fWinSize.width() - frame->width()) / 2, |
| 48 |
(fWinSize.height() - frame->height()) / 2); |
| 49 |
|
| 50 |
SkPaint outline_paint; |
| 51 |
outline_paint.setAntiAlias(true); |
| 52 |
outline_paint.setColor(0x80000000); |
| 53 |
outline_paint.setStyle(SkPaint::kStroke_Style); |
| 54 |
|
| 55 |
const SkRect outline = SkRect::Make(frame->bounds()).makeOutset(1, 1); |
| 56 |
canvas->drawRect(outline, outline_paint); |
| 57 |
|
| 58 |
canvas->drawImage(frame, 0, 0); |
| 59 |
} |
| 60 |
|
| 61 |
bool AnimatedImageSlide::animate(double nanos) { |
| 62 |
if (!fImageAsset || !fImageAsset->isMultiFrame()) { |
| 63 |
return false; |
| 64 |
} |
| 65 |
|
| 66 |
if (!fTimeBase) { |
| 67 |
fTimeBase = nanos; |
| 68 |
} |
| 69 |
|
| 70 |
fFrameMs = std::fmod((nanos - fTimeBase) * 0.000001f, fImageAsset->duration()); |
| 71 |
|
| 72 |
return true; |
| 73 |
} |
| 74 |
|
| 75 |
DEF_SLIDE( return new AnimatedImageSlide(SkString("AnimatedImage"), |
| 76 |
SkString("images/alphabetAnim.gif")); ) |