/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.graphics.drawable; import android.graphics.Insets; import android.graphics.Xfermode; import android.os.Trace; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.NinePatch; import android.graphics.PixelFormat; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.Region; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.StateSet; import android.util.TypedValue; import android.util.Xml; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.util.Arrays; /** * A Drawable is a general abstraction for "something that can be drawn." Most * often you will deal with Drawable as the type of resource retrieved for * drawing things to the screen; the Drawable class provides a generic API for * dealing with an underlying visual resource that may take a variety of forms. * Unlike a {@link android.view.View}, a Drawable does not have any facility to * receive events or otherwise interact with the user. * *
In addition to simple drawing, Drawable provides a number of generic * mechanisms for its client to interact with what is being drawn: * *
For more information about how to use drawables, read the * Canvas and Drawables developer * guide. For information and examples of creating drawable resources (XML or bitmap files that * can be loaded in code), read the * Drawable Resources * document.
If the new state you are supplying causes the appearance of the * Drawable to change, then it is responsible for calling * {@link #invalidateSelf} in order to have itself redrawn, and * true will be returned from this function. * *
Note: The Drawable holds a reference on to stateSet * until a new state array is given to it, so you must not modify this * array during that time.
* * @param stateSet The new set of states to be displayed. * * @return Returns true if this change in state has caused the appearance * of the Drawable to change (hence requiring an invalidate), otherwise * returns false. */ public boolean setState(final int[] stateSet) { if (!Arrays.equals(mStateSet, stateSet)) { mStateSet = stateSet; return onStateChange(stateSet); } return false; } /** * Describes the current state, as a union of primitve states, such as * {@link android.R.attr#state_focused}, * {@link android.R.attr#state_selected}, etc. * Some drawables may modify their imagery based on the selected state. * @return An array of resource Ids describing the current state. */ public int[] getState() { return mStateSet; } /** * If this Drawable does transition animations between states, ask that * it immediately jump to the current state and skip any active animations. */ public void jumpToCurrentState() { } /** * @return The current drawable that will be used by this drawable. For simple drawables, this * is just the drawable itself. For drawables that change state like * {@link StateListDrawable} and {@link LevelListDrawable} this will be the child drawable * currently in use. */ public Drawable getCurrent() { return this; } /** * Specify the level for the drawable. This allows a drawable to vary its * imagery based on a continuous controller, for example to show progress * or volume level. * *If the new level you are supplying causes the appearance of the * Drawable to change, then it is responsible for calling * {@link #invalidateSelf} in order to have itself redrawn, and * true will be returned from this function. * * @param level The new level, from 0 (minimum) to 10000 (maximum). * * @return Returns true if this change in level has caused the appearance * of the Drawable to change (hence requiring an invalidate), otherwise * returns false. */ public final boolean setLevel(int level) { if (mLevel != level) { mLevel = level; return onLevelChange(level); } return false; } /** * Retrieve the current level. * * @return int Current level, from 0 (minimum) to 10000 (maximum). */ public final int getLevel() { return mLevel; } /** * Set whether this Drawable is visible. This generally does not impact * the Drawable's behavior, but is a hint that can be used by some * Drawables, for example, to decide whether run animations. * * @param visible Set to true if visible, false if not. * @param restart You can supply true here to force the drawable to behave * as if it has just become visible, even if it had last * been set visible. Used for example to force animations * to restart. * * @return boolean Returns true if the new visibility is different than * its previous state. */ public boolean setVisible(boolean visible, boolean restart) { boolean changed = mVisible != visible; if (changed) { mVisible = visible; invalidateSelf(); } return changed; } public final boolean isVisible() { return mVisible; } /** * Set whether this Drawable is automatically mirrored when its layout direction is RTL * (right-to left). See {@link android.util.LayoutDirection}. * * @param mirrored Set to true if the Drawable should be mirrored, false if not. */ public void setAutoMirrored(boolean mirrored) { } /** * Tells if this Drawable will be automatically mirrored when its layout direction is RTL * right-to-left. See {@link android.util.LayoutDirection}. * * @return boolean Returns true if this Drawable will be automatically mirrored. */ public boolean isAutoMirrored() { return false; } /** * Return the opacity/transparency of this Drawable. The returned value is * one of the abstract format constants in * {@link android.graphics.PixelFormat}: * {@link android.graphics.PixelFormat#UNKNOWN}, * {@link android.graphics.PixelFormat#TRANSLUCENT}, * {@link android.graphics.PixelFormat#TRANSPARENT}, or * {@link android.graphics.PixelFormat#OPAQUE}. * *
Generally a Drawable should be as conservative as possible with the * value it returns. For example, if it contains multiple child drawables * and only shows one of them at a time, if only one of the children is * TRANSLUCENT and the others are OPAQUE then TRANSLUCENT should be * returned. You can use the method {@link #resolveOpacity} to perform a * standard reduction of two opacities to the appropriate single output. * *
Note that the returned value does not take into account a * custom alpha or color filter that has been applied by the client through * the {@link #setAlpha} or {@link #setColorFilter} methods. * * @return int The opacity class of the Drawable. * * @see android.graphics.PixelFormat */ public abstract int getOpacity(); /** * Return the appropriate opacity value for two source opacities. If * either is UNKNOWN, that is returned; else, if either is TRANSLUCENT, * that is returned; else, if either is TRANSPARENT, that is returned; * else, OPAQUE is returned. * *
This is to help in implementing {@link #getOpacity}. * * @param op1 One opacity value. * @param op2 Another opacity value. * * @return int The combined opacity value. * * @see #getOpacity */ public static int resolveOpacity(int op1, int op2) { if (op1 == op2) { return op1; } if (op1 == PixelFormat.UNKNOWN || op2 == PixelFormat.UNKNOWN) { return PixelFormat.UNKNOWN; } if (op1 == PixelFormat.TRANSLUCENT || op2 == PixelFormat.TRANSLUCENT) { return PixelFormat.TRANSLUCENT; } if (op1 == PixelFormat.TRANSPARENT || op2 == PixelFormat.TRANSPARENT) { return PixelFormat.TRANSPARENT; } return PixelFormat.OPAQUE; } /** * Returns a Region representing the part of the Drawable that is completely * transparent. This can be used to perform drawing operations, identifying * which parts of the target will not change when rendering the Drawable. * The default implementation returns null, indicating no transparent * region; subclasses can optionally override this to return an actual * Region if they want to supply this optimization information, but it is * not required that they do so. * * @return Returns null if the Drawables has no transparent region to * report, else a Region holding the parts of the Drawable's bounds that * are transparent. */ public Region getTransparentRegion() { return null; } /** * Override this in your subclass to change appearance if you recognize the * specified state. * * @return Returns true if the state change has caused the appearance of * the Drawable to change (that is, it needs to be drawn), else false * if it looks the same and there is no need to redraw it since its * last state. */ protected boolean onStateChange(int[] state) { return false; } /** Override this in your subclass to change appearance if you vary based * on level. * @return Returns true if the level change has caused the appearance of * the Drawable to change (that is, it needs to be drawn), else false * if it looks the same and there is no need to redraw it since its * last level. */ protected boolean onLevelChange(int level) { return false; } /** * Override this in your subclass to change appearance if you vary based on * the bounds. */ protected void onBoundsChange(Rect bounds) {} /** * Return the intrinsic width of the underlying drawable object. Returns * -1 if it has no intrinsic width, such as with a solid color. */ public int getIntrinsicWidth() { return -1; } /** * Return the intrinsic height of the underlying drawable object. Returns * -1 if it has no intrinsic height, such as with a solid color. */ public int getIntrinsicHeight() { return -1; } /** * Returns the minimum width suggested by this Drawable. If a View uses this * Drawable as a background, it is suggested that the View use at least this * value for its width. (There will be some scenarios where this will not be * possible.) This value should INCLUDE any padding. * * @return The minimum width suggested by this Drawable. If this Drawable * doesn't have a suggested minimum width, 0 is returned. */ public int getMinimumWidth() { final int intrinsicWidth = getIntrinsicWidth(); return intrinsicWidth > 0 ? intrinsicWidth : 0; } /** * Returns the minimum height suggested by this Drawable. If a View uses this * Drawable as a background, it is suggested that the View use at least this * value for its height. (There will be some scenarios where this will not be * possible.) This value should INCLUDE any padding. * * @return The minimum height suggested by this Drawable. If this Drawable * doesn't have a suggested minimum height, 0 is returned. */ public int getMinimumHeight() { final int intrinsicHeight = getIntrinsicHeight(); return intrinsicHeight > 0 ? intrinsicHeight : 0; } /** * Return in padding the insets suggested by this Drawable for placing * content inside the drawable's bounds. Positive values move toward the * center of the Drawable (set Rect.inset). Returns true if this drawable * actually has a padding, else false. When false is returned, the padding * is always set to 0. */ public boolean getPadding(Rect padding) { padding.set(0, 0, 0, 0); return false; } /** * Return in insets the layout insets suggested by this Drawable for use with alignment * operations during layout. * * @hide */ public Insets getOpticalInsets() { return Insets.NONE; } /** * Make this drawable mutable. This operation cannot be reversed. A mutable * drawable is guaranteed to not share its state with any other drawable. * This is especially useful when you need to modify properties of drawables * loaded from resources. By default, all drawables instances loaded from * the same resource share a common state; if you modify the state of one * instance, all the other instances will receive the same modification. * * Calling this method on a mutable Drawable will have no effect. * * @return This drawable. * @see ConstantState * @see #getConstantState() */ public Drawable mutate() { return this; } /** * Create a drawable from an inputstream */ public static Drawable createFromStream(InputStream is, String srcName) { Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable"); try { return createFromResourceStream(null, null, is, srcName, null); } finally { Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); } } /** * Create a drawable from an inputstream, using the given resources and * value to determine density information. */ public static Drawable createFromResourceStream(Resources res, TypedValue value, InputStream is, String srcName) { Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable"); try { return createFromResourceStream(res, value, is, srcName, null); } finally { Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); } } /** * Create a drawable from an inputstream, using the given resources and * value to determine density information. */ public static Drawable createFromResourceStream(Resources res, TypedValue value, InputStream is, String srcName, BitmapFactory.Options opts) { if (is == null) { return null; } /* ugh. The decodeStream contract is that we have already allocated the pad rect, but if the bitmap does not had a ninepatch chunk, then the pad will be ignored. If we could change this to lazily alloc/assign the rect, we could avoid the GC churn of making new Rects only to drop them on the floor. */ Rect pad = new Rect(); // Special stuff for compatibility mode: if the target density is not // the same as the display density, but the resource -is- the same as // the display density, then don't scale it down to the target density. // This allows us to load the system's density-correct resources into // an application in compatibility mode, without scaling those down // to the compatibility density only to have them scaled back up when // drawn to the screen. if (opts == null) opts = new BitmapFactory.Options(); opts.inScreenDensity = res != null ? res.getDisplayMetrics().noncompatDensityDpi : DisplayMetrics.DENSITY_DEVICE; Bitmap bm = BitmapFactory.decodeResourceStream(res, value, is, pad, opts); if (bm != null) { byte[] np = bm.getNinePatchChunk(); if (np == null || !NinePatch.isNinePatchChunk(np)) { np = null; pad = null; } int[] layoutBounds = bm.getLayoutBounds(); Rect layoutBoundsRect = null; if (layoutBounds != null) { layoutBoundsRect = new Rect(layoutBounds[0], layoutBounds[1], layoutBounds[2], layoutBounds[3]); } return drawableFromBitmap(res, bm, np, pad, layoutBoundsRect, srcName); } return null; } /** * Create a drawable from an XML document. For more information on how to * create resources in XML, see * Drawable Resources. */ public static Drawable createFromXml(Resources r, XmlPullParser parser) throws XmlPullParserException, IOException { AttributeSet attrs = Xml.asAttributeSet(parser); int type; while ((type=parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty loop } if (type != XmlPullParser.START_TAG) { throw new XmlPullParserException("No start tag found"); } Drawable drawable = createFromXmlInner(r, parser, attrs); if (drawable == null) { throw new RuntimeException("Unknown initial tag: " + parser.getName()); } return drawable; } /** * Create from inside an XML document. Called on a parser positioned at * a tag in an XML document, tries to create a Drawable from that tag. * Returns null if the tag is not a valid drawable. */ public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs) throws XmlPullParserException, IOException { Drawable drawable; final String name = parser.getName(); if (name.equals("selector")) { drawable = new StateListDrawable(); } else if (name.equals("level-list")) { drawable = new LevelListDrawable(); } else if (name.equals("layer-list")) { drawable = new LayerDrawable(); } else if (name.equals("transition")) { drawable = new TransitionDrawable(); } else if (name.equals("color")) { drawable = new ColorDrawable(); } else if (name.equals("shape")) { drawable = new GradientDrawable(); } else if (name.equals("scale")) { drawable = new ScaleDrawable(); } else if (name.equals("clip")) { drawable = new ClipDrawable(); } else if (name.equals("rotate")) { drawable = new RotateDrawable(); } else if (name.equals("animated-rotate")) { drawable = new AnimatedRotateDrawable(); } else if (name.equals("animation-list")) { drawable = new AnimationDrawable(); } else if (name.equals("inset")) { drawable = new InsetDrawable(); } else if (name.equals("bitmap")) { //noinspection deprecation drawable = new BitmapDrawable(r); if (r != null) { ((BitmapDrawable) drawable).setTargetDensity(r.getDisplayMetrics()); } } else if (name.equals("nine-patch")) { drawable = new NinePatchDrawable(); if (r != null) { ((NinePatchDrawable) drawable).setTargetDensity(r.getDisplayMetrics()); } } else { throw new XmlPullParserException(parser.getPositionDescription() + ": invalid drawable tag " + name); } drawable.inflate(r, parser, attrs); return drawable; } /** * Create a drawable from file path name. */ public static Drawable createFromPath(String pathName) { if (pathName == null) { return null; } Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, pathName); try { Bitmap bm = BitmapFactory.decodeFile(pathName); if (bm != null) { return drawableFromBitmap(null, bm, null, null, null, pathName); } } finally { Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); } return null; } /** * Inflate this Drawable from an XML resource. */ public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) throws XmlPullParserException, IOException { TypedArray a = r.obtainAttributes(attrs, com.android.internal.R.styleable.Drawable); inflateWithAttributes(r, parser, a, com.android.internal.R.styleable.Drawable_visible); a.recycle(); } /** * Inflate a Drawable from an XML resource. * * @throws XmlPullParserException * @throws IOException */ void inflateWithAttributes(Resources r, XmlPullParser parser, TypedArray attrs, int visibleAttr) throws XmlPullParserException, IOException { mVisible = attrs.getBoolean(visibleAttr, mVisible); } /** * This abstract class is used by {@link Drawable}s to store shared constant state and data * between Drawables. {@link BitmapDrawable}s created from the same resource will for instance * share a unique bitmap stored in their ConstantState. * *
* {@link #newDrawable(Resources)} can be used as a factory to create new Drawable instances * from this ConstantState. *
* * Use {@link Drawable#getConstantState()} to retrieve the ConstantState of a Drawable. Calling * {@link Drawable#mutate()} on a Drawable should typically create a new ConstantState for that * Drawable. */ public static abstract class ConstantState { /** * Create a new drawable without supplying resources the caller * is running in. Note that using this means the density-dependent * drawables (like bitmaps) will not be able to update their target * density correctly. One should use {@link #newDrawable(Resources)} * instead to provide a resource. */ public abstract Drawable newDrawable(); /** * Create a new Drawable instance from its constant state. This * must be implemented for drawables that change based on the target * density of their caller (that is depending on whether it is * in compatibility mode). */ public Drawable newDrawable(Resources res) { return newDrawable(); } /** * Return a bit mask of configuration changes that will impact * this drawable (and thus require completely reloading it). */ public abstract int getChangingConfigurations(); /** * @hide */ public Bitmap getBitmap() { return null; } } /** * Return a {@link ConstantState} instance that holds the shared state of this Drawable. *q * @return The ConstantState associated to that Drawable. * @see ConstantState * @see Drawable#mutate() */ public ConstantState getConstantState() { return null; } private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np, Rect pad, Rect layoutBounds, String srcName) { if (np != null) { return new NinePatchDrawable(res, bm, np, pad, layoutBounds, srcName); } return new BitmapDrawable(res, bm); } }