1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.graphics;
18 
19 /**
20  * The NinePatch class permits drawing a bitmap in nine or more sections.
21  * Essentially, it allows the creation of custom graphics that will scale the
22  * way that you define, when content added within the image exceeds the normal
23  * bounds of the graphic. For a thorough explanation of a NinePatch image,
24  * read the discussion in the
25  * <a href="{@docRoot}guide/topics/graphics/2d-graphics.html#nine-patch">2D
26  * Graphics</a> document.
27  * <p>
28  * The <a href="{@docRoot}guide/developing/tools/draw9patch.html">Draw 9-Patch</a>
29  * tool offers an extremely handy way to create your NinePatch images,
30  * using a WYSIWYG graphics editor.
31  * </p>
32  */
33 public class NinePatch {
34     /**
35      * Struct of inset information attached to a 9 patch bitmap.
36      *
37      * Present on a 9 patch bitmap if it optical insets were manually included,
38      * or if outline insets were automatically included by aapt.
39      *
40      * @hide
41      */
42     public static class InsetStruct {
43         @SuppressWarnings({"UnusedDeclaration"}) // called from JNI
InsetStruct(int opticalLeft, int opticalTop, int opticalRight, int opticalBottom, int outlineLeft, int outlineTop, int outlineRight, int outlineBottom, float outlineRadius, int outlineAlpha, float decodeScale)44         InsetStruct(int opticalLeft, int opticalTop, int opticalRight, int opticalBottom,
45                 int outlineLeft, int outlineTop, int outlineRight, int outlineBottom,
46                 float outlineRadius, int outlineAlpha, float decodeScale) {
47             opticalRect = new Rect(opticalLeft, opticalTop, opticalRight, opticalBottom);
48             opticalRect.scale(decodeScale);
49 
50             outlineRect = scaleInsets(outlineLeft, outlineTop,
51                     outlineRight, outlineBottom, decodeScale);
52 
53             this.outlineRadius = outlineRadius * decodeScale;
54             this.outlineAlpha = outlineAlpha / 255.0f;
55         }
56 
57         public final Rect opticalRect;
58         public final Rect outlineRect;
59         public final float outlineRadius;
60         public final float outlineAlpha;
61 
62         /**
63          * Scales up the rect by the given scale, ceiling values, so actual outline Rect
64          * grows toward the inside.
65          */
scaleInsets(int left, int top, int right, int bottom, float scale)66         public static Rect scaleInsets(int left, int top, int right, int bottom, float scale) {
67             if (scale == 1.0f) {
68                 return new Rect(left, top, right, bottom);
69             }
70 
71             Rect result = new Rect();
72             result.left = (int) Math.ceil(left * scale);
73             result.top = (int) Math.ceil(top * scale);
74             result.right = (int) Math.ceil(right * scale);
75             result.bottom = (int) Math.ceil(bottom * scale);
76             return  result;
77         }
78     }
79 
80     private final Bitmap mBitmap;
81 
82     /**
83      * Used by native code. This pointer is an instance of Res_png_9patch*.
84      *
85      * @hide
86      */
87     public long mNativeChunk;
88 
89     private Paint mPaint;
90     private String mSrcName;
91 
92     /**
93      * Create a drawable projection from a bitmap to nine patches.
94      *
95      * @param bitmap The bitmap describing the patches.
96      * @param chunk The 9-patch data chunk describing how the underlying bitmap
97      *              is split apart and drawn.
98      */
NinePatch(Bitmap bitmap, byte[] chunk)99     public NinePatch(Bitmap bitmap, byte[] chunk) {
100         this(bitmap, chunk, null);
101     }
102 
103     /**
104      * Create a drawable projection from a bitmap to nine patches.
105      *
106      * @param bitmap The bitmap describing the patches.
107      * @param chunk The 9-patch data chunk describing how the underlying
108      *              bitmap is split apart and drawn.
109      * @param srcName The name of the source for the bitmap. Might be null.
110      */
NinePatch(Bitmap bitmap, byte[] chunk, String srcName)111     public NinePatch(Bitmap bitmap, byte[] chunk, String srcName) {
112         mBitmap = bitmap;
113         mSrcName = srcName;
114         mNativeChunk = validateNinePatchChunk(chunk);
115     }
116 
117     /**
118      * @hide
119      */
NinePatch(NinePatch patch)120     public NinePatch(NinePatch patch) {
121         mBitmap = patch.mBitmap;
122         mSrcName = patch.mSrcName;
123         if (patch.mPaint != null) {
124             mPaint = new Paint(patch.mPaint);
125         }
126         // No need to validate the 9patch chunk again, it was done by
127         // the instance we're copying from
128         mNativeChunk = patch.mNativeChunk;
129     }
130 
131     @Override
finalize()132     protected void finalize() throws Throwable {
133         try {
134             if (mNativeChunk != 0) {
135                 // only attempt to destroy correctly initilized chunks
136                 nativeFinalize(mNativeChunk);
137                 mNativeChunk = 0;
138             }
139         } finally {
140             super.finalize();
141         }
142     }
143 
144     /**
145      * Returns the name of this NinePatch object if one was specified
146      * when calling the constructor.
147      */
getName()148     public String getName() {
149         return mSrcName;
150     }
151 
152     /**
153      * Returns the paint used to draw this NinePatch. The paint can be null.
154      *
155      * @see #setPaint(Paint)
156      * @see #draw(Canvas, Rect)
157      * @see #draw(Canvas, RectF)
158      */
getPaint()159     public Paint getPaint() {
160         return mPaint;
161     }
162 
163     /**
164      * Sets the paint to use when drawing the NinePatch.
165      *
166      * @param p The paint that will be used to draw this NinePatch.
167      *
168      * @see #getPaint()
169      * @see #draw(Canvas, Rect)
170      * @see #draw(Canvas, RectF)
171      */
setPaint(Paint p)172     public void setPaint(Paint p) {
173         mPaint = p;
174     }
175 
176     /**
177      * Returns the bitmap used to draw this NinePatch.
178      */
getBitmap()179     public Bitmap getBitmap() {
180         return mBitmap;
181     }
182 
183     /**
184      * Draws the NinePatch. This method will use the paint returned by {@link #getPaint()}.
185      *
186      * @param canvas A container for the current matrix and clip used to draw the NinePatch.
187      * @param location Where to draw the NinePatch.
188      */
draw(Canvas canvas, RectF location)189     public void draw(Canvas canvas, RectF location) {
190         canvas.drawPatch(this, location, mPaint);
191     }
192 
193     /**
194      * Draws the NinePatch. This method will use the paint returned by {@link #getPaint()}.
195      *
196      * @param canvas A container for the current matrix and clip used to draw the NinePatch.
197      * @param location Where to draw the NinePatch.
198      */
draw(Canvas canvas, Rect location)199     public void draw(Canvas canvas, Rect location) {
200         canvas.drawPatch(this, location, mPaint);
201     }
202 
203     /**
204      * Draws the NinePatch. This method will ignore the paint returned
205      * by {@link #getPaint()} and use the specified paint instead.
206      *
207      * @param canvas A container for the current matrix and clip used to draw the NinePatch.
208      * @param location Where to draw the NinePatch.
209      * @param paint The Paint to draw through.
210      */
draw(Canvas canvas, Rect location, Paint paint)211     public void draw(Canvas canvas, Rect location, Paint paint) {
212         canvas.drawPatch(this, location, paint);
213     }
214 
215     /**
216      * Return the underlying bitmap's density, as per
217      * {@link Bitmap#getDensity() Bitmap.getDensity()}.
218      */
getDensity()219     public int getDensity() {
220         return mBitmap.mDensity;
221     }
222 
223     /**
224      * Returns the intrinsic width, in pixels, of this NinePatch. This is equivalent
225      * to querying the width of the underlying bitmap returned by {@link #getBitmap()}.
226      */
getWidth()227     public int getWidth() {
228         return mBitmap.getWidth();
229     }
230 
231     /**
232      * Returns the intrinsic height, in pixels, of this NinePatch. This is equivalent
233      * to querying the height of the underlying bitmap returned by {@link #getBitmap()}.
234      */
getHeight()235     public int getHeight() {
236         return mBitmap.getHeight();
237     }
238 
239     /**
240      * Indicates whether this NinePatch contains transparent or translucent pixels.
241      * This is equivalent to calling <code>getBitmap().hasAlpha()</code> on this
242      * NinePatch.
243      */
hasAlpha()244     public final boolean hasAlpha() {
245         return mBitmap.hasAlpha();
246     }
247 
248     /**
249      * Returns a {@link Region} representing the parts of the NinePatch that are
250      * completely transparent.
251      *
252      * @param bounds The location and size of the NinePatch.
253      *
254      * @return null if the NinePatch has no transparent region to
255      * report, else a {@link Region} holding the parts of the specified bounds
256      * that are transparent.
257      */
getTransparentRegion(Rect bounds)258     public final Region getTransparentRegion(Rect bounds) {
259         long r = nativeGetTransparentRegion(mBitmap, mNativeChunk, bounds);
260         return r != 0 ? new Region(r) : null;
261     }
262 
263     /**
264      * Verifies that the specified byte array is a valid 9-patch data chunk.
265      *
266      * @param chunk A byte array representing a 9-patch data chunk.
267      *
268      * @return True if the specified byte array represents a 9-patch data chunk,
269      *         false otherwise.
270      */
isNinePatchChunk(byte[] chunk)271     public native static boolean isNinePatchChunk(byte[] chunk);
272 
273     /**
274      * Validates the 9-patch chunk and throws an exception if the chunk is invalid.
275      * If validation is successful, this method returns a native Res_png_9patch*
276      * object used by the renderers.
277      */
validateNinePatchChunk(byte[] chunk)278     private static native long validateNinePatchChunk(byte[] chunk);
nativeFinalize(long chunk)279     private static native void nativeFinalize(long chunk);
nativeGetTransparentRegion(Bitmap bitmap, long chunk, Rect location)280     private static native long nativeGetTransparentRegion(Bitmap bitmap, long chunk, Rect location);
281 }
282