Drawable.java revision 70588bf864f961974c93aace7586d3e2773a54a8
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
17package android.graphics.drawable;
18
19import org.xmlpull.v1.XmlPullParser;
20import org.xmlpull.v1.XmlPullParserException;
21
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.BitmapFactory;
26import android.graphics.Canvas;
27import android.graphics.ColorFilter;
28import android.graphics.NinePatch;
29import android.graphics.PixelFormat;
30import android.graphics.PorterDuff;
31import android.graphics.PorterDuffColorFilter;
32import android.graphics.Rect;
33import android.graphics.Region;
34import android.util.AttributeSet;
35import android.util.DisplayMetrics;
36import android.util.StateSet;
37import android.util.TypedValue;
38import android.util.Xml;
39
40import java.io.IOException;
41import java.io.InputStream;
42import java.lang.ref.WeakReference;
43import java.util.Arrays;
44
45/**
46 * A Drawable is a general abstraction for "something that can be drawn."  Most
47 * often you will deal with Drawable as the type of resource retrieved for
48 * drawing things to the screen; the Drawable class provides a generic API for
49 * dealing with an underlying visual resource that may take a variety of forms.
50 * Unlike a {@link android.view.View}, a Drawable does not have any facility to
51 * receive events or otherwise interact with the user.
52 *
53 * <p>In addition to simple drawing, Drawable provides a number of generic
54 * mechanisms for its client to interact with what is being drawn:
55 *
56 * <ul>
57 *     <li> The {@link #setBounds} method <var>must</var> be called to tell the
58 *     Drawable where it is drawn and how large it should be.  All Drawables
59 *     should respect the requested size, often simply by scaling their
60 *     imagery.  A client can find the preferred size for some Drawables with
61 *     the {@link #getIntrinsicHeight} and {@link #getIntrinsicWidth} methods.
62 *
63 *     <li> The {@link #getPadding} method can return from some Drawables
64 *     information about how to frame content that is placed inside of them.
65 *     For example, a Drawable that is intended to be the frame for a button
66 *     widget would need to return padding that correctly places the label
67 *     inside of itself.
68 *
69 *     <li> The {@link #setState} method allows the client to tell the Drawable
70 *     in which state it is to be drawn, such as "focused", "selected", etc.
71 *     Some drawables may modify their imagery based on the selected state.
72 *
73 *     <li> The {@link #setLevel} method allows the client to supply a single
74 *     continuous controller that can modify the Drawable is displayed, such as
75 *     a battery level or progress level.  Some drawables may modify their
76 *     imagery based on the current level.
77 *
78 *     <li> A Drawable can perform animations by calling back to its client
79 *     through the {@link Callback} interface.  All clients should support this
80 *     interface (via {@link #setCallback}) so that animations will work.  A
81 *     simple way to do this is through the system facilities such as
82 *     {@link android.view.View#setBackgroundDrawable(Drawable)} and
83 *     {@link android.widget.ImageView}.
84 * </ul>
85 *
86 * Though usually not visible to the application, Drawables may take a variety
87 * of forms:
88 *
89 * <ul>
90 *     <li> <b>Bitmap</b>: the simplest Drawable, a PNG or JPEG image.
91 *     <li> <b>Nine Patch</b>: an extension to the PNG format allows it to
92 *     specify information about how to stretch it and place things inside of
93 *     it.
94 *     <li> <b>Shape</b>: contains simple drawing commands instead of a raw
95 *     bitmap, allowing it to resize better in some cases.
96 *     <li> <b>Layers</b>: a compound drawable, which draws multiple underlying
97 *     drawables on top of each other.
98 *     <li> <b>States</b>: a compound drawable that selects one of a set of
99 *     drawables based on its state.
100 *     <li> <b>Levels</b>: a compound drawable that selects one of a set of
101 *     drawables based on its level.
102 *     <li> <b>Scale</b>: a compound drawable with a single child drawable,
103 *     whose overall size is modified based on the current level.
104 * </ul>
105 * <p>For information and examples of creating drawable resources (XML or bitmap files that
106 * can be loaded in code), see <a
107 * href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.
108 */
109public abstract class Drawable {
110    private static final Rect ZERO_BOUNDS_RECT = new Rect();
111
112    private int[] mStateSet = StateSet.WILD_CARD;
113    private int mLevel = 0;
114    private int mChangingConfigurations = 0;
115    private Rect mBounds = ZERO_BOUNDS_RECT;  // lazily becomes a new Rect()
116    private WeakReference<Callback> mCallback = null;
117    private boolean mVisible = true;
118
119    /**
120     * Draw in its bounds (set via setBounds) respecting optional effects such
121     * as alpha (set via setAlpha) and color filter (set via setColorFilter).
122     *
123     * @param canvas The canvas to draw into
124     */
125    public abstract void draw(Canvas canvas);
126
127    /**
128     * Specify a bounding rectangle for the Drawable. This is where the drawable
129     * will draw when its draw() method is called.
130     */
131    public void setBounds(int left, int top, int right, int bottom) {
132        Rect oldBounds = mBounds;
133
134        if (oldBounds == ZERO_BOUNDS_RECT) {
135            oldBounds = mBounds = new Rect();
136        }
137
138        if (oldBounds.left != left || oldBounds.top != top ||
139                oldBounds.right != right || oldBounds.bottom != bottom) {
140            mBounds.set(left, top, right, bottom);
141            onBoundsChange(mBounds);
142        }
143    }
144
145    /**
146     * Specify a bounding rectangle for the Drawable. This is where the drawable
147     * will draw when its draw() method is called.
148     */
149    public void setBounds(Rect bounds) {
150        setBounds(bounds.left, bounds.top, bounds.right, bounds.bottom);
151    }
152
153    /**
154     * Return a copy of the drawable's bounds in the specified Rect (allocated
155     * by the caller). The bounds specify where this will draw when its draw()
156     * method is called.
157     *
158     * @param bounds Rect to receive the drawable's bounds (allocated by the
159     *               caller).
160     */
161    public final void copyBounds(Rect bounds) {
162        bounds.set(mBounds);
163    }
164
165    /**
166     * Return a copy of the drawable's bounds in a new Rect. This returns the
167     * same values as getBounds(), but the returned object is guaranteed to not
168     * be changed later by the drawable (i.e. it retains no reference to this
169     * rect). If the caller already has a Rect allocated, call copyBounds(rect).
170     *
171     * @return A copy of the drawable's bounds
172     */
173    public final Rect copyBounds() {
174        return new Rect(mBounds);
175    }
176
177    /**
178     * Return the drawable's bounds Rect. Note: for efficiency, the returned
179     * object may be the same object stored in the drawable (though this is not
180     * guaranteed), so if a persistent copy of the bounds is needed, call
181     * copyBounds(rect) instead.
182     * You should also not change the object returned by this method as it may
183     * be the same object stored in the drawable.
184     *
185     * @return The bounds of the drawable (which may change later, so caller
186     *         beware). DO NOT ALTER the returned object as it may change the
187     *         stored bounds of this drawable.
188     *
189     * @see #copyBounds()
190     * @see #copyBounds(android.graphics.Rect)
191     */
192    public final Rect getBounds() {
193        if (mBounds == ZERO_BOUNDS_RECT) {
194            mBounds = new Rect();
195        }
196
197        return mBounds;
198    }
199
200    /**
201     * Set a mask of the configuration parameters for which this drawable
202     * may change, requiring that it be re-created.
203     *
204     * @param configs A mask of the changing configuration parameters, as
205     * defined by {@link android.content.res.Configuration}.
206     *
207     * @see android.content.res.Configuration
208     */
209    public void setChangingConfigurations(int configs) {
210        mChangingConfigurations = configs;
211    }
212
213    /**
214     * Return a mask of the configuration parameters for which this drawable
215     * may change, requiring that it be re-created.  The default implementation
216     * returns whatever was provided through
217     * {@link #setChangingConfigurations(int)} or 0 by default.  Subclasses
218     * may extend this to or in the changing configurations of any other
219     * drawables they hold.
220     *
221     * @return Returns a mask of the changing configuration parameters, as
222     * defined by {@link android.content.res.Configuration}.
223     *
224     * @see android.content.res.Configuration
225     */
226    public int getChangingConfigurations() {
227        return mChangingConfigurations;
228    }
229
230    /**
231     * Set to true to have the drawable dither its colors when drawn to a device
232     * with fewer than 8-bits per color component. This can improve the look on
233     * those devices, but can also slow down the drawing a little.
234     */
235    public void setDither(boolean dither) {}
236
237    /**
238     * Set to true to have the drawable filter its bitmap when scaled or rotated
239     * (for drawables that use bitmaps). If the drawable does not use bitmaps,
240     * this call is ignored. This can improve the look when scaled or rotated,
241     * but also slows down the drawing.
242     */
243    public void setFilterBitmap(boolean filter) {}
244
245    /**
246     * Implement this interface if you want to create an animated drawable that
247     * extends {@link android.graphics.drawable.Drawable Drawable}.
248     * Upon retrieving a drawable, use
249     * {@link Drawable#setCallback(android.graphics.drawable.Drawable.Callback)}
250     * to supply your implementation of the interface to the drawable; it uses
251     * this interface to schedule and execute animation changes.
252     */
253    public static interface Callback {
254        /**
255         * Called when the drawable needs to be redrawn.  A view at this point
256         * should invalidate itself (or at least the part of itself where the
257         * drawable appears).
258         *
259         * @param who The drawable that is requesting the update.
260         */
261        public void invalidateDrawable(Drawable who);
262
263        /**
264         * A Drawable can call this to schedule the next frame of its
265         * animation.  An implementation can generally simply call
266         * {@link android.os.Handler#postAtTime(Runnable, Object, long)} with
267         * the parameters <var>(what, who, when)</var> to perform the
268         * scheduling.
269         *
270         * @param who The drawable being scheduled.
271         * @param what The action to execute.
272         * @param when The time (in milliseconds) to run.  The timebase is
273         *             {@link android.os.SystemClock#uptimeMillis}
274         */
275        public void scheduleDrawable(Drawable who, Runnable what, long when);
276
277        /**
278         * A Drawable can call this to unschedule an action previously
279         * scheduled with {@link #scheduleDrawable}.  An implementation can
280         * generally simply call
281         * {@link android.os.Handler#removeCallbacks(Runnable, Object)} with
282         * the parameters <var>(what, who)</var> to unschedule the drawable.
283         *
284         * @param who The drawable being unscheduled.
285         * @param what The action being unscheduled.
286         */
287        public void unscheduleDrawable(Drawable who, Runnable what);
288    }
289
290    /**
291     * Bind a {@link Callback} object to this Drawable.  Required for clients
292     * that want to support animated drawables.
293     *
294     * @param cb The client's Callback implementation.
295     *
296     * @see #getCallback()
297     */
298    public final void setCallback(Callback cb) {
299        mCallback = new WeakReference<Callback>(cb);
300    }
301
302    /**
303     * Return the current {@link Callback} implementation attached to this
304     * Drawable.
305     *
306     * @return A {@link Callback} instance or null if no callback was set.
307     *
308     * @see #setCallback(android.graphics.drawable.Drawable.Callback)
309     */
310    public Callback getCallback() {
311        if (mCallback != null) {
312            return mCallback.get();
313        }
314        return null;
315    }
316
317    /**
318     * Use the current {@link Callback} implementation to have this Drawable
319     * redrawn.  Does nothing if there is no Callback attached to the
320     * Drawable.
321     *
322     * @see Callback#invalidateDrawable
323     * @see #getCallback()
324     * @see #setCallback(android.graphics.drawable.Drawable.Callback)
325     */
326    public void invalidateSelf() {
327        final Callback callback = getCallback();
328        if (callback != null) {
329            callback.invalidateDrawable(this);
330        }
331    }
332
333    /**
334     * Use the current {@link Callback} implementation to have this Drawable
335     * scheduled.  Does nothing if there is no Callback attached to the
336     * Drawable.
337     *
338     * @param what The action being scheduled.
339     * @param when The time (in milliseconds) to run.
340     *
341     * @see Callback#scheduleDrawable
342     */
343    public void scheduleSelf(Runnable what, long when) {
344        final Callback callback = getCallback();
345        if (callback != null) {
346            callback.scheduleDrawable(this, what, when);
347        }
348    }
349
350    /**
351     * Use the current {@link Callback} implementation to have this Drawable
352     * unscheduled.  Does nothing if there is no Callback attached to the
353     * Drawable.
354     *
355     * @param what The runnable that you no longer want called.
356     *
357     * @see Callback#unscheduleDrawable
358     */
359    public void unscheduleSelf(Runnable what) {
360        final Callback callback = getCallback();
361        if (callback != null) {
362            callback.unscheduleDrawable(this, what);
363        }
364    }
365
366    /**
367     * Specify an alpha value for the drawable. 0 means fully transparent, and
368     * 255 means fully opaque.
369     */
370    public abstract void setAlpha(int alpha);
371
372    /**
373     * Specify an optional colorFilter for the drawable. Pass null to remove
374     * any filters.
375    */
376    public abstract void setColorFilter(ColorFilter cf);
377
378    /**
379     * Specify a color and porterduff mode to be the colorfilter for this
380     * drawable.
381     */
382    public void setColorFilter(int color, PorterDuff.Mode mode) {
383        setColorFilter(new PorterDuffColorFilter(color, mode));
384    }
385
386    public void clearColorFilter() {
387        setColorFilter(null);
388    }
389
390    /**
391     * Indicates whether this view will change its appearance based on state.
392     * Clients can use this to determine whether it is necessary to calculate
393     * their state and call setState.
394     *
395     * @return True if this view changes its appearance based on state, false
396     *         otherwise.
397     *
398     * @see #setState(int[])
399     */
400    public boolean isStateful() {
401        return false;
402    }
403
404    /**
405     * Specify a set of states for the drawable. These are use-case specific,
406     * so see the relevant documentation. As an example, the background for
407     * widgets like Button understand the following states:
408     * [{@link android.R.attr#state_focused},
409     *  {@link android.R.attr#state_pressed}].
410     *
411     * <p>If the new state you are supplying causes the appearance of the
412     * Drawable to change, then it is responsible for calling
413     * {@link #invalidateSelf} in order to have itself redrawn, <em>and</em>
414     * true will be returned from this function.
415     *
416     * <p>Note: The Drawable holds a reference on to <var>stateSet</var>
417     * until a new state array is given to it, so you must not modify this
418     * array during that time.</p>
419     *
420     * @param stateSet The new set of states to be displayed.
421     *
422     * @return Returns true if this change in state has caused the appearance
423     * of the Drawable to change (hence requiring an invalidate), otherwise
424     * returns false.
425     */
426    public boolean setState(final int[] stateSet) {
427        if (!Arrays.equals(mStateSet, stateSet)) {
428            mStateSet = stateSet;
429            return onStateChange(stateSet);
430        }
431        return false;
432    }
433
434    /**
435     * Describes the current state, as a union of primitve states, such as
436     * {@link android.R.attr#state_focused},
437     * {@link android.R.attr#state_selected}, etc.
438     * Some drawables may modify their imagery based on the selected state.
439     * @return An array of resource Ids describing the current state.
440     */
441    public int[] getState() {
442        return mStateSet;
443    }
444
445    /**
446     * If this Drawable does transition animations between states, ask that
447     * it immediately jump to the current state and skip any active animations.
448     */
449    public void jumpToCurrentState() {
450    }
451
452    /**
453     * @return The current drawable that will be used by this drawable. For simple drawables, this
454     *         is just the drawable itself. For drawables that change state like
455     *         {@link StateListDrawable} and {@link LevelListDrawable} this will be the child drawable
456     *         currently in use.
457     */
458    public Drawable getCurrent() {
459        return this;
460    }
461
462    /**
463     * Specify the level for the drawable.  This allows a drawable to vary its
464     * imagery based on a continuous controller, for example to show progress
465     * or volume level.
466     *
467     * <p>If the new level you are supplying causes the appearance of the
468     * Drawable to change, then it is responsible for calling
469     * {@link #invalidateSelf} in order to have itself redrawn, <em>and</em>
470     * true will be returned from this function.
471     *
472     * @param level The new level, from 0 (minimum) to 10000 (maximum).
473     *
474     * @return Returns true if this change in level has caused the appearance
475     * of the Drawable to change (hence requiring an invalidate), otherwise
476     * returns false.
477     */
478    public final boolean setLevel(int level) {
479        if (mLevel != level) {
480            mLevel = level;
481            return onLevelChange(level);
482        }
483        return false;
484    }
485
486    /**
487     * Retrieve the current level.
488     *
489     * @return int Current level, from 0 (minimum) to 10000 (maximum).
490     */
491    public final int getLevel() {
492        return mLevel;
493    }
494
495    /**
496     * Set whether this Drawable is visible.  This generally does not impact
497     * the Drawable's behavior, but is a hint that can be used by some
498     * Drawables, for example, to decide whether run animations.
499     *
500     * @param visible Set to true if visible, false if not.
501     * @param restart You can supply true here to force the drawable to behave
502     *                as if it has just become visible, even if it had last
503     *                been set visible.  Used for example to force animations
504     *                to restart.
505     *
506     * @return boolean Returns true if the new visibility is different than
507     *         its previous state.
508     */
509    public boolean setVisible(boolean visible, boolean restart) {
510        boolean changed = mVisible != visible;
511        if (changed) {
512            mVisible = visible;
513            invalidateSelf();
514        }
515        return changed;
516    }
517
518    public final boolean isVisible() {
519        return mVisible;
520    }
521
522    /**
523     * Return the opacity/transparency of this Drawable.  The returned value is
524     * one of the abstract format constants in
525     * {@link android.graphics.PixelFormat}:
526     * {@link android.graphics.PixelFormat#UNKNOWN},
527     * {@link android.graphics.PixelFormat#TRANSLUCENT},
528     * {@link android.graphics.PixelFormat#TRANSPARENT}, or
529     * {@link android.graphics.PixelFormat#OPAQUE}.
530     *
531     * <p>Generally a Drawable should be as conservative as possible with the
532     * value it returns.  For example, if it contains multiple child drawables
533     * and only shows one of them at a time, if only one of the children is
534     * TRANSLUCENT and the others are OPAQUE then TRANSLUCENT should be
535     * returned.  You can use the method {@link #resolveOpacity} to perform a
536     * standard reduction of two opacities to the appropriate single output.
537     *
538     * <p>Note that the returned value does <em>not</em> take into account a
539     * custom alpha or color filter that has been applied by the client through
540     * the {@link #setAlpha} or {@link #setColorFilter} methods.
541     *
542     * @return int The opacity class of the Drawable.
543     *
544     * @see android.graphics.PixelFormat
545     */
546    public abstract int getOpacity();
547
548    /**
549     * Return the appropriate opacity value for two source opacities.  If
550     * either is UNKNOWN, that is returned; else, if either is TRANSLUCENT,
551     * that is returned; else, if either is TRANSPARENT, that is returned;
552     * else, OPAQUE is returned.
553     *
554     * <p>This is to help in implementing {@link #getOpacity}.
555     *
556     * @param op1 One opacity value.
557     * @param op2 Another opacity value.
558     *
559     * @return int The combined opacity value.
560     *
561     * @see #getOpacity
562     */
563    public static int resolveOpacity(int op1, int op2) {
564        if (op1 == op2) {
565            return op1;
566        }
567        if (op1 == PixelFormat.UNKNOWN || op2 == PixelFormat.UNKNOWN) {
568            return PixelFormat.UNKNOWN;
569        }
570        if (op1 == PixelFormat.TRANSLUCENT || op2 == PixelFormat.TRANSLUCENT) {
571            return PixelFormat.TRANSLUCENT;
572        }
573        if (op1 == PixelFormat.TRANSPARENT || op2 == PixelFormat.TRANSPARENT) {
574            return PixelFormat.TRANSPARENT;
575        }
576        return PixelFormat.OPAQUE;
577    }
578
579    /**
580     * Returns a Region representing the part of the Drawable that is completely
581     * transparent.  This can be used to perform drawing operations, identifying
582     * which parts of the target will not change when rendering the Drawable.
583     * The default implementation returns null, indicating no transparent
584     * region; subclasses can optionally override this to return an actual
585     * Region if they want to supply this optimization information, but it is
586     * not required that they do so.
587     *
588     * @return Returns null if the Drawables has no transparent region to
589     * report, else a Region holding the parts of the Drawable's bounds that
590     * are transparent.
591     */
592    public Region getTransparentRegion() {
593        return null;
594    }
595
596    /**
597     * Override this in your subclass to change appearance if you recognize the
598     * specified state.
599     *
600     * @return Returns true if the state change has caused the appearance of
601     * the Drawable to change (that is, it needs to be drawn), else false
602     * if it looks the same and there is no need to redraw it since its
603     * last state.
604     */
605    protected boolean onStateChange(int[] state) { return false; }
606    /** Override this in your subclass to change appearance if you vary based
607     *  on level.
608     * @return Returns true if the level change has caused the appearance of
609     * the Drawable to change (that is, it needs to be drawn), else false
610     * if it looks the same and there is no need to redraw it since its
611     * last level.
612     */
613    protected boolean onLevelChange(int level) { return false; }
614    /**
615     * Override this in your subclass to change appearance if you recognize the
616     * specified state.
617     */
618    protected void onBoundsChange(Rect bounds) {}
619
620    /**
621     * Return the intrinsic width of the underlying drawable object.  Returns
622     * -1 if it has no intrinsic width, such as with a solid color.
623     */
624    public int getIntrinsicWidth() {
625        return -1;
626    }
627
628    /**
629     * Return the intrinsic height of the underlying drawable object. Returns
630     * -1 if it has no intrinsic height, such as with a solid color.
631     */
632    public int getIntrinsicHeight() {
633        return -1;
634    }
635
636    /**
637     * Returns the minimum width suggested by this Drawable. If a View uses this
638     * Drawable as a background, it is suggested that the View use at least this
639     * value for its width. (There will be some scenarios where this will not be
640     * possible.) This value should INCLUDE any padding.
641     *
642     * @return The minimum width suggested by this Drawable. If this Drawable
643     *         doesn't have a suggested minimum width, 0 is returned.
644     */
645    public int getMinimumWidth() {
646        final int intrinsicWidth = getIntrinsicWidth();
647        return intrinsicWidth > 0 ? intrinsicWidth : 0;
648    }
649
650    /**
651     * Returns the minimum height suggested by this Drawable. If a View uses this
652     * Drawable as a background, it is suggested that the View use at least this
653     * value for its height. (There will be some scenarios where this will not be
654     * possible.) This value should INCLUDE any padding.
655     *
656     * @return The minimum height suggested by this Drawable. If this Drawable
657     *         doesn't have a suggested minimum height, 0 is returned.
658     */
659    public int getMinimumHeight() {
660        final int intrinsicHeight = getIntrinsicHeight();
661        return intrinsicHeight > 0 ? intrinsicHeight : 0;
662    }
663
664    /**
665     * Return in padding the insets suggested by this Drawable for placing
666     * content inside the drawable's bounds. Positive values move toward the
667     * center of the Drawable (set Rect.inset). Returns true if this drawable
668     * actually has a padding, else false. When false is returned, the padding
669     * is always set to 0.
670     */
671    public boolean getPadding(Rect padding) {
672        padding.set(0, 0, 0, 0);
673        return false;
674    }
675
676    /**
677     * Make this drawable mutable. This operation cannot be reversed. A mutable
678     * drawable is guaranteed to not share its state with any other drawable.
679     * This is especially useful when you need to modify properties of drawables
680     * loaded from resources. By default, all drawables instances loaded from
681     * the same resource share a common state; if you modify the state of one
682     * instance, all the other instances will receive the same modification.
683     *
684     * Calling this method on a mutable Drawable will have no effect.
685     *
686     * @return This drawable.
687     * @see ConstantState
688     * @see #getConstantState()
689     */
690    public Drawable mutate() {
691        return this;
692    }
693
694    /**
695     * Create a drawable from an inputstream
696     */
697    public static Drawable createFromStream(InputStream is, String srcName) {
698        return createFromResourceStream(null, null, is, srcName, null);
699    }
700
701    /**
702     * Create a drawable from an inputstream, using the given resources and
703     * value to determine density information.
704     */
705    public static Drawable createFromResourceStream(Resources res, TypedValue value,
706            InputStream is, String srcName) {
707        return createFromResourceStream(res, value, is, srcName, null);
708    }
709
710    /**
711     * Create a drawable from an inputstream, using the given resources and
712     * value to determine density information.
713     */
714    public static Drawable createFromResourceStream(Resources res, TypedValue value,
715            InputStream is, String srcName, BitmapFactory.Options opts) {
716
717        if (is == null) {
718            return null;
719        }
720
721        /*  ugh. The decodeStream contract is that we have already allocated
722            the pad rect, but if the bitmap does not had a ninepatch chunk,
723            then the pad will be ignored. If we could change this to lazily
724            alloc/assign the rect, we could avoid the GC churn of making new
725            Rects only to drop them on the floor.
726        */
727        Rect pad = new Rect();
728
729        // Special stuff for compatibility mode: if the target density is not
730        // the same as the display density, but the resource -is- the same as
731        // the display density, then don't scale it down to the target density.
732        // This allows us to load the system's density-correct resources into
733        // an application in compatibility mode, without scaling those down
734        // to the compatibility density only to have them scaled back up when
735        // drawn to the screen.
736        if (opts == null) opts = new BitmapFactory.Options();
737        opts.inScreenDensity = DisplayMetrics.DENSITY_DEVICE;
738        Bitmap  bm = BitmapFactory.decodeResourceStream(res, value, is, pad, opts);
739        if (bm != null) {
740            byte[] np = bm.getNinePatchChunk();
741            if (np == null || !NinePatch.isNinePatchChunk(np)) {
742                np = null;
743                pad = null;
744            }
745            return drawableFromBitmap(res, bm, np, pad, srcName);
746        }
747        return null;
748    }
749
750    /**
751     * Create a drawable from an XML document. For more information on how to
752     * create resources in XML, see
753     * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.
754     */
755    public static Drawable createFromXml(Resources r, XmlPullParser parser)
756            throws XmlPullParserException, IOException {
757        AttributeSet attrs = Xml.asAttributeSet(parser);
758
759        int type;
760        while ((type=parser.next()) != XmlPullParser.START_TAG &&
761                type != XmlPullParser.END_DOCUMENT) {
762            // Empty loop
763        }
764
765        if (type != XmlPullParser.START_TAG) {
766            throw new XmlPullParserException("No start tag found");
767        }
768
769        Drawable drawable = createFromXmlInner(r, parser, attrs);
770
771        if (drawable == null) {
772            throw new RuntimeException("Unknown initial tag: " + parser.getName());
773        }
774
775        return drawable;
776    }
777
778    /**
779     * Create from inside an XML document.  Called on a parser positioned at
780     * a tag in an XML document, tries to create a Drawable from that tag.
781     * Returns null if the tag is not a valid drawable.
782     */
783    public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs)
784    throws XmlPullParserException, IOException {
785        Drawable drawable;
786
787        final String name = parser.getName();
788
789        if (name.equals("selector")) {
790            drawable = new StateListDrawable();
791        } else if (name.equals("level-list")) {
792            drawable = new LevelListDrawable();
793        /* Probably not doing this.
794        } else if (name.equals("mipmap")) {
795            drawable = new MipmapDrawable();
796        */
797        } else if (name.equals("layer-list")) {
798            drawable = new LayerDrawable();
799        } else if (name.equals("transition")) {
800            drawable = new TransitionDrawable();
801        } else if (name.equals("color")) {
802            drawable = new ColorDrawable();
803        } else if (name.equals("shape")) {
804            drawable = new GradientDrawable();
805        } else if (name.equals("scale")) {
806            drawable = new ScaleDrawable();
807        } else if (name.equals("clip")) {
808            drawable = new ClipDrawable();
809        } else if (name.equals("rotate")) {
810            drawable = new RotateDrawable();
811        } else if (name.equals("animated-rotate")) {
812            drawable = new AnimatedRotateDrawable();
813        } else if (name.equals("animation-list")) {
814            drawable = new AnimationDrawable();
815        } else if (name.equals("inset")) {
816            drawable = new InsetDrawable();
817        } else if (name.equals("bitmap")) {
818            drawable = new BitmapDrawable(r);
819            if (r != null) {
820               ((BitmapDrawable) drawable).setTargetDensity(r.getDisplayMetrics());
821            }
822        } else if (name.equals("nine-patch")) {
823            drawable = new NinePatchDrawable();
824            if (r != null) {
825                ((NinePatchDrawable) drawable).setTargetDensity(r.getDisplayMetrics());
826             }
827        } else {
828            throw new XmlPullParserException(parser.getPositionDescription() +
829                    ": invalid drawable tag " + name);
830        }
831
832        drawable.inflate(r, parser, attrs);
833        return drawable;
834    }
835
836
837    /**
838     * Create a drawable from file path name.
839     */
840    public static Drawable createFromPath(String pathName) {
841        if (pathName == null) {
842            return null;
843        }
844
845        Bitmap bm = BitmapFactory.decodeFile(pathName);
846        if (bm != null) {
847            return drawableFromBitmap(null, bm, null, null, pathName);
848        }
849
850        return null;
851    }
852
853    /**
854     * Inflate this Drawable from an XML resource.
855     */
856    public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs)
857            throws XmlPullParserException, IOException {
858
859        TypedArray a = r.obtainAttributes(attrs, com.android.internal.R.styleable.Drawable);
860        inflateWithAttributes(r, parser, a, com.android.internal.R.styleable.Drawable_visible);
861        a.recycle();
862    }
863
864    /**
865     * Inflate a Drawable from an XML resource.
866     *
867     * @throws XmlPullParserException
868     * @throws IOException
869     */
870    void inflateWithAttributes(Resources r, XmlPullParser parser,
871            TypedArray attrs, int visibleAttr)
872            throws XmlPullParserException, IOException {
873
874        mVisible = attrs.getBoolean(visibleAttr, mVisible);
875    }
876
877    /**
878     * This abstract class is used by {@link Drawable}s to store shared constant state and data
879     * between Drawables. {@link BitmapDrawable}s created from the same resource will for instance
880     * share a unique bitmap stored in their ConstantState.
881     *
882     * <p>
883     * {@link #newDrawable(Resources)} can be used as a factory to create new Drawable instances
884     * from this ConstantState.
885     * </p>
886     *
887     * Use {@link Drawable#getConstantState()} to retrieve the ConstantState of a Drawable. Calling
888     * {@link Drawable#mutate()} on a Drawable should typically create a new ConstantState for that
889     * Drawable.
890     */
891    public static abstract class ConstantState {
892        /**
893         * Create a new drawable without supplying resources the caller
894         * is running in.  Note that using this means the density-dependent
895         * drawables (like bitmaps) will not be able to update their target
896         * density correctly. One should use {@link #newDrawable(Resources)}
897         * instead to provide a resource.
898         */
899        public abstract Drawable newDrawable();
900        /**
901         * Create a new Drawable instance from its constant state.  This
902         * must be implemented for drawables that change based on the target
903         * density of their caller (that is depending on whether it is
904         * in compatibility mode).
905         */
906        public Drawable newDrawable(Resources res) {
907            return newDrawable();
908        }
909        /**
910         * Return a bit mask of configuration changes that will impact
911         * this drawable (and thus require completely reloading it).
912         */
913        public abstract int getChangingConfigurations();
914    }
915
916    /**
917     * Return a {@link ConstantState} instance that holds the shared state of this Drawable.
918     *q
919     * @return The ConstantState associated to that Drawable.
920     * @see ConstantState
921     * @see Drawable#mutate()
922     */
923    public ConstantState getConstantState() {
924        return null;
925    }
926
927    private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np,
928            Rect pad, String srcName) {
929
930        if (np != null) {
931            return new NinePatchDrawable(res, bm, np, pad, srcName);
932        }
933
934        return new BitmapDrawable(res, bm);
935    }
936}
937
938