1 /*
2  * Copyright 2011 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 "SampleCode.h"
9 #include "SkCanvas.h"
10 #include "SkPaint.h"
11 #include "SkPath.h"
12 #include "SkView.h"
13 
14 ///////////////////////////////////////////////////////////////////////////////
15 
16 class LayerMaskView : public SampleView {
17 public:
LayerMaskView()18     LayerMaskView() {
19         this->setBGColor(0xFFDDDDDD);
20     }
21 
22 protected:
23     // overrides from SkEventSink
onQuery(SkEvent * evt)24     virtual bool onQuery(SkEvent* evt) {
25         if (SampleCode::TitleQ(*evt)) {
26             SampleCode::TitleR(evt, "LayerMask");
27             return true;
28         }
29         return this->INHERITED::onQuery(evt);
30     }
31 
drawMask(SkCanvas * canvas,const SkRect & r)32     void drawMask(SkCanvas* canvas, const SkRect& r) {
33         SkPaint paint;
34         paint.setAntiAlias(true);
35 
36         if (true) {
37             SkBitmap mask;
38             int w = SkScalarRoundToInt(r.width());
39             int h = SkScalarRoundToInt(r.height());
40             mask.allocN32Pixels(w, h);
41             mask.eraseColor(SK_ColorTRANSPARENT);
42             SkCanvas c(mask);
43             SkRect bounds = r;
44             bounds.offset(-bounds.fLeft, -bounds.fTop);
45             c.drawOval(bounds, paint);
46 
47             paint.setXfermodeMode(SkXfermode::kDstIn_Mode);
48             canvas->drawBitmap(mask, r.fLeft, r.fTop, &paint);
49         } else {
50             SkPath p;
51             p.addOval(r);
52             p.setFillType(SkPath::kInverseWinding_FillType);
53             paint.setXfermodeMode(SkXfermode::kDstOut_Mode);
54             canvas->drawPath(p, paint);
55         }
56     }
57 
onDrawContent(SkCanvas * canvas)58     virtual void onDrawContent(SkCanvas* canvas) {
59         SkRect  r;
60         r.set(SkIntToScalar(20), SkIntToScalar(20), SkIntToScalar(120), SkIntToScalar(120));
61         canvas->saveLayer(&r, nullptr);
62         canvas->drawColor(SK_ColorRED);
63         drawMask(canvas, r);
64         canvas->restore();
65     }
66 
67 private:
68     typedef SampleView INHERITED;
69 };
70 
71 ///////////////////////////////////////////////////////////////////////////////
72 
MyFactory()73 static SkView* MyFactory() { return new LayerMaskView; }
74 static SkViewRegister reg(MyFactory);
75