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