• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 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 "gm.h"
9 #include "sk_tool_utils.h"
10 #include "SkCanvas.h"
11 #include "SkPaint.h"
12 #include "SkRandom.h"
13 #include "SkSurface.h"
14 
15 namespace skiagm {
16 
17 /*
18  * This GM exercises SkCanvas::discard() by creating an offscreen SkSurface and repeatedly
19  * discarding it, drawing to it, and then drawing it to the main canvas.
20  */
21 class DiscardGM : public GpuGM {
22 
23 public:
DiscardGM()24     DiscardGM() {
25     }
26 
27 protected:
onShortName()28     SkString onShortName() override {
29         return SkString("discard");
30     }
31 
onISize()32     SkISize onISize() override {
33         return SkISize::Make(100, 100);
34     }
35 
onDraw(GrContext * context,GrRenderTargetContext *,SkCanvas * canvas,SkString * errorMsg)36     DrawResult onDraw(GrContext* context, GrRenderTargetContext*, SkCanvas* canvas,
37                       SkString* errorMsg) override {
38         SkISize size = this->getISize();
39         size.fWidth /= 10;
40         size.fHeight /= 10;
41         SkImageInfo info = SkImageInfo::MakeN32Premul(size);
42         auto surface = SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info);
43         if (nullptr == surface) {
44             *errorMsg = "Could not create render target.";
45             return DrawResult::kFail;
46         }
47 
48         canvas->clear(SK_ColorBLACK);
49 
50         SkRandom rand;
51         for (int x = 0; x < 10; ++x) {
52             for (int y = 0; y < 10; ++y) {
53               surface->getCanvas()->discard();
54               // Make something that isn't too close to the background color, black.
55               SkColor color = sk_tool_utils::color_to_565(rand.nextU() | 0xFF404040);
56               switch (rand.nextULessThan(3)) {
57                   case 0:
58                       surface->getCanvas()->drawColor(color);
59                       break;
60                   case 1:
61                       surface->getCanvas()->clear(color);
62                       break;
63                   case 2:
64                       SkPaint paint;
65                       paint.setShader(SkShader::MakeColorShader(color));
66                       surface->getCanvas()->drawPaint(paint);
67                       break;
68               }
69               surface->draw(canvas, 10.f*x, 10.f*y, nullptr);
70             }
71         }
72 
73         surface->getCanvas()->discard();
74         return DrawResult::kOk;
75     }
76 
77 private:
78     typedef GM INHERITED;
79 };
80 
81 //////////////////////////////////////////////////////////////////////////////
82 
83 DEF_GM(return new DiscardGM;)
84 
85 } // end namespace
86