1 /*
2  * Copyright 2015 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 "SkNinePatchIter.h"
9 #include "SkRect.h"
10 
Valid(int width,int height,const SkIRect & center)11 bool SkNinePatchIter::Valid(int width, int height, const SkIRect& center) {
12     return !center.isEmpty() && SkIRect::MakeWH(width, height).contains(center);
13 }
14 
SkNinePatchIter(int w,int h,const SkIRect & c,const SkRect & dst)15 SkNinePatchIter::SkNinePatchIter(int w, int h, const SkIRect& c, const SkRect& dst) {
16     SkASSERT(SkIRect::MakeWH(w, h).contains(c));
17 
18     fSrcX[0] = 0;
19     fSrcX[1] = SkIntToScalar(c.fLeft);
20     fSrcX[2] = SkIntToScalar(c.fRight);
21     fSrcX[3] = SkIntToScalar(w);
22 
23     fSrcY[0] = 0;
24     fSrcY[1] = SkIntToScalar(c.fTop);
25     fSrcY[2] = SkIntToScalar(c.fBottom);
26     fSrcY[3] = SkIntToScalar(h);
27 
28     fDstX[0] = dst.fLeft;
29     fDstX[1] = dst.fLeft + SkIntToScalar(c.fLeft);
30     fDstX[2] = dst.fRight - SkIntToScalar(w - c.fRight);
31     fDstX[3] = dst.fRight;
32 
33     fDstY[0] = dst.fTop;
34     fDstY[1] = dst.fTop + SkIntToScalar(c.fTop);
35     fDstY[2] = dst.fBottom - SkIntToScalar(h - c.fBottom);
36     fDstY[3] = dst.fBottom;
37 
38     if (fDstX[1] > fDstX[2]) {
39         fDstX[1] = fDstX[0] + (fDstX[3] - fDstX[0]) * c.fLeft / (w - c.width());
40         fDstX[2] = fDstX[1];
41     }
42 
43     if (fDstY[1] > fDstY[2]) {
44         fDstY[1] = fDstY[0] + (fDstY[3] - fDstY[0]) * c.fTop / (h - c.height());
45         fDstY[2] = fDstY[1];
46     }
47 
48     fCurrX = fCurrY = 0;
49     fDone = false;
50 }
51 
next(SkRect * src,SkRect * dst)52 bool SkNinePatchIter::next(SkRect* src, SkRect* dst) {
53     if (fDone) {
54         return false;
55     }
56 
57     const int x = fCurrX;
58     const int y = fCurrY;
59     SkASSERT(x >= 0 && x < 3);
60     SkASSERT(y >= 0 && y < 3);
61 
62     src->set(fSrcX[x], fSrcY[y], fSrcX[x + 1], fSrcY[y + 1]);
63     dst->set(fDstX[x], fDstY[y], fDstX[x + 1], fDstY[y + 1]);
64     if (3 == ++fCurrX) {
65         fCurrX = 0;
66         fCurrY += 1;
67         if (fCurrY >= 3) {
68             fDone = true;
69         }
70     }
71     return true;
72 }
73