标签:
/* * 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.annotation.NonNull; import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.Resources.Theme; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Insets; import android.graphics.NinePatch; import android.graphics.Outline; import android.graphics.PixelFormat; import android.graphics.PorterDuff; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.Region; import android.graphics.Xfermode; import android.os.Trace; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.StateSet; import android.util.TypedValue; import android.util.Xml; import android.view.View; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.util.Arrays; import java.util.Collection; /** * 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. * Drawable是一个常见的抽象类,意味着可以被绘制的东西。你处理Drawable的大多数情况是把它当 * 做绘制在屏幕上的一种资源。Drawable通过了一些API用于处理不同类型的视觉资源,而不像View。 * Drawable没有任何的接收事件或者和用户交互的特性。 * <p>In addition to simple drawing, Drawable provides a number of generic * mechanisms for its client to interact with what is being drawn: * 除了简单的绘制,Drawable通过了一系列机制为客户端和被绘制的对象进行交互。 * <ul> * <li> The {@link #setBounds} method <var>must</var> be called to tell the * Drawable where it is drawn and how large it should be. All Drawables * should respect the requested size, often simply by scaling their * imagery. A client can find the preferred size for some Drawables with * the {@link #getIntrinsicHeight} and {@link #getIntrinsicWidth} methods. * * <li> The {@link #getPadding} method can return from some Drawables * information about how to frame content that is placed inside of them. * For example, a Drawable that is intended to be the frame for a button * widget would need to return padding that correctly places the label * inside of itself. * * <li> The {@link #setState} method allows the client to tell the Drawable * in which state it is to be drawn, such as "focused", "selected", etc. * Some drawables may modify their imagery based on the selected state. * * <li> The {@link #setLevel} method allows the client to supply a single * continuous controller that can modify the Drawable is displayed, such as * a battery level or progress level. Some drawables may modify their * imagery based on the current level. * * <li> A Drawable can perform animations by calling back to its client * through the {@link Callback} interface. All clients should support this * interface (via {@link #setCallback}) so that animations will work. A * simple way to do this is through the system facilities such as * {@link android.view.View#setBackground(Drawable)} and * {@link android.widget.ImageView}. * </ul> * * Though usually not visible to the application, Drawables may take a variety * of forms: * * <ul> * <li> <b>Bitmap</b>: the simplest Drawable, a PNG or JPEG image. * <li> <b>Nine Patch</b>: an extension to the PNG format allows it to * specify information about how to stretch it and place things inside of * it. * <li> <b>Shape</b>: contains simple drawing commands instead of a raw * bitmap, allowing it to resize better in some cases. * <li> <b>Layers</b>: a compound drawable, which draws multiple underlying * drawables on top of each other. * <li> <b>States</b>: a compound drawable that selects one of a set of * drawables based on its state. * <li> <b>Levels</b>: a compound drawable that selects one of a set of * drawables based on its level. * <li> <b>Scale</b>: a compound drawable with a single child drawable, * whose overall size is modified based on the current level. * </ul> * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about how to use drawables, read the * <a href="{@docRoot}guide/topics/graphics/2d-graphics.html">Canvas and Drawables</a> developer * guide. For information and examples of creating drawable resources (XML or bitmap files that * can be loaded in code), read the * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a> * document.</p></div> */ public abstract class Drawable { private static final Rect ZERO_BOUNDS_RECT = new Rect(); static final PorterDuff.Mode DEFAULT_TINT_MODE = PorterDuff.Mode.SRC_IN; private int[] mStateSet = StateSet.WILD_CARD; private int mLevel = 0; private int mChangingConfigurations = 0; private Rect mBounds = ZERO_BOUNDS_RECT; // lazily becomes a new Rect() private WeakReference<Callback> mCallback = null; private boolean mVisible = true; private int mLayoutDirection; /** * Draw in its bounds (set via setBounds) respecting optional effects such * as alpha (set via setAlpha) and color filter (set via setColorFilter). * 在它的边界内绘制一些相关可选的效果,例如透明度,颜色过滤 * @param canvas The canvas to draw into */ public abstract void draw(Canvas canvas); /** * Specify a bounding rectangle for the Drawable. This is where the drawable * will draw when its draw() method is called. * 为Drawable设置一个边界矩形。当draw()方法被调用,这个矩形是drawable会被绘制到的地方。 */ public void setBounds(int left, int top, int right, int bottom) { Rect oldBounds = mBounds; if (oldBounds == ZERO_BOUNDS_RECT) { oldBounds = mBounds = new Rect(); } if (oldBounds.left != left || oldBounds.top != top || oldBounds.right != right || oldBounds.bottom != bottom) { if (!oldBounds.isEmpty()) { // first invalidate the previous bounds invalidateSelf(); } mBounds.set(left, top, right, bottom); onBoundsChange(mBounds); } } /** * Specify a bounding rectangle for the Drawable. This is where the drawable * will draw when its draw() method is called. * 为Drawable设置一个边界矩形。当draw()方法被调用,这个矩形是drawable会被绘制到的地方。 */ public void setBounds(Rect bounds) { setBounds(bounds.left, bounds.top, bounds.right, bounds.bottom); } /** * Return a copy of the drawable's bounds in the specified Rect (allocated * by the caller). The bounds specify where this will draw when its draw() * method is called. * 返回Drawable的bounds的复制 * @param bounds Rect to receive the drawable's bounds (allocated by the * caller). */ public final void copyBounds(Rect bounds) { bounds.set(mBounds); } /** * Return a copy of the drawable's bounds in a new Rect. This returns the * same values as getBounds(), but the returned object is guaranteed to not * be changed later by the drawable (i.e. it retains no reference to this * rect). If the caller already has a Rect allocated, call copyBounds(rect). * 返回Drawable的bounds的复制。这个和getBounds()返回一样的值,不过返回的是拷贝,保证 * 这个对象不会被drawabel修改. * @return A copy of the drawable's bounds */ public final Rect copyBounds() { return new Rect(mBounds); } /** * Return the drawable's bounds Rect. Note: for efficiency, the returned * object may be the same object stored in the drawable (though this is not * guaranteed), so if a persistent copy of the bounds is needed, call * copyBounds(rect) instead. * You should also not change the object returned by this method as it may * be the same object stored in the drawable. * 返回drawable的边界矩形。你不应该修改返回的对象,因为它可能和drawable里面的是同一个 * 引用。 * @return The bounds of the drawable (which may change later, so caller * beware). DO NOT ALTER the returned object as it may change the * stored bounds of this drawable. * * @see #copyBounds() * @see #copyBounds(android.graphics.Rect) */ public final Rect getBounds() { if (mBounds == ZERO_BOUNDS_RECT) { mBounds = new Rect(); } return mBounds; } /** * Return the drawable's dirty bounds Rect. Note: for efficiency, the * returned object may be the same object stored in the drawable (though * this is not guaranteed). * 获取脏的边界矩形。 * <p> * By default, this returns the full drawable bounds. Custom drawables may * override this method to perform more precise invalidation. * 默认返回整个矩形。常见的drawable可能会重载这个方法来实现更精确的失效。 * @return The dirty bounds of this drawable */ public Rect getDirtyBounds() { return getBounds(); } /** * Set a mask of the configuration parameters for which this drawable * may change, requiring that it be re-created. * * @param configs A mask of the changing configuration parameters, as * defined by {@link android.content.pm.ActivityInfo}. * * @see android.content.pm.ActivityInfo */ public void setChangingConfigurations(int configs) { mChangingConfigurations = configs; } /** * Return a mask of the configuration parameters for which this drawable * may change, requiring that it be re-created. The default implementation * returns whatever was provided through * {@link #setChangingConfigurations(int)} or 0 by default. Subclasses * may extend this to or in the changing configurations of any other * drawables they hold. * * @return Returns a mask of the changing configuration parameters, as * defined by {@link android.content.pm.ActivityInfo}. * * @see android.content.pm.ActivityInfo */ public int getChangingConfigurations() { return mChangingConfigurations; } /** * Set to true to have the drawable dither its colors when drawn to a device * with fewer than 8-bits per color component. This can improve the look on * those devices, but can also slow down the drawing a little. * 设置为true,当华仔设备生的每个颜色组件小于8位时,保证drawable颜色效果。这个可以提高 * 外观,但是会稍微减慢绘制。 */ public void setDither(boolean dither) {} /** * Set to true to have the drawable filter its bitmap when scaled or rotated * (for drawables that use bitmaps). If the drawable does not use bitmaps, * this call is ignored. This can improve the look when scaled or rotated, * but also slows down the drawing. * 设置为true,drawable在被缩放或旋转的时候,会过滤它的bitmap(为那些使用bitmap的drawable准备)。 * 如果drawable没有使用bitmap,这个设置会被忽略。在缩放和旋转时这个可以提高外观,但是会稍微减慢绘制。 */ public void setFilterBitmap(boolean filter) {} /** * Implement this interface if you want to create an animated drawable that * extends {@link android.graphics.drawable.Drawable Drawable}. * Upon retrieving a drawable, use * {@link Drawable#setCallback(android.graphics.drawable.Drawable.Callback)} * to supply your implementation of the interface to the drawable; it uses * this interface to schedule and execute animation changes. * 继承这个接口如果你想创建一个继承自drawable动画drawable。对于drawable,使用它的setCallback() * 方法去提供这个接口的实现。它使用这个接口去定时和执行动画转变。 */ public static interface Callback { /** * Called when the drawable needs to be redrawn. A view at this point * should invalidate itself (or at least the part of itself where the * drawable appears). * 当drawable需要重绘时,调用这个方法。View在这里应该使自己不可用(或者至少使drawable * 出现的部分不可用)。 * @param who The drawable that is requesting the update. */ public void invalidateDrawable(Drawable who); /** * A Drawable can call this to schedule the next frame of its * animation. An implementation can generally simply call * {@link android.os.Handler#postAtTime(Runnable, Object, long)} with * the parameters <var>(what, who, when)</var> to perform the * scheduling. * Drawable通过这个方法去安排动画的下一帧。实现者可以简单地调用android.os.Handler#postAtTime(Runnable, Object, long) * @param who The drawable being scheduled. * @param what The action to execute. * @param when The time (in milliseconds) to run. The timebase is * {@link android.os.SystemClock#uptimeMillis} */ public void scheduleDrawable(Drawable who, Runnable what, long when); /** * A Drawable can call this to unschedule an action previously * scheduled with {@link #scheduleDrawable}. An implementation can * generally simply call * {@link android.os.Handler#removeCallbacks(Runnable, Object)} with * the parameters <var>(what, who)</var> to unschedule the drawable. * Drawable通过这个方法去取消scheduleDrawable()方法安排的行为。 * @param who The drawable being unscheduled. * @param what The action being unscheduled. */ public void unscheduleDrawable(Drawable who, Runnable what); } /** * Bind a {@link Callback} object to this Drawable. Required for clients * that want to support animated drawables. * 给Drawable绑定一个Callback对象。那些使用动态drawables的客户端会需要。 * @param cb The client's Callback implementation. * * @see #getCallback() */ public final void setCallback(Callback cb) { mCallback = new WeakReference<Callback>(cb); } /** * Return the current {@link Callback} implementation attached to this * Drawable. * 返回绑定在当前drawable的Callback实现 * @return A {@link Callback} instance or null if no callback was set. * * @see #setCallback(android.graphics.drawable.Drawable.Callback) */ public Callback getCallback() { if (mCallback != null) { return mCallback.get(); } return null; } /** * Use the current {@link Callback} implementation to have this Drawable * redrawn. Does nothing if there is no Callback attached to the * Drawable. * 使用当前Callback的实现去使这个Drawable重绘。如果没有为Drawable设置Callable, * 则什么都不做 * @see Callback#invalidateDrawable * @see #getCallback() * @see #setCallback(android.graphics.drawable.Drawable.Callback) */ public void invalidateSelf() { final Callback callback = getCallback(); if (callback != null) { callback.invalidateDrawable(this); } } /** * Use the current {@link Callback} implementation to have this Drawable * scheduled. Does nothing if there is no Callback attached to the * Drawable. * 使用当前Callback的实现去使这个Drawable定时。如果没有为Drawable设置Callable, * @param what The action being scheduled. * @param when The time (in milliseconds) to run. * * @see Callback#scheduleDrawable */ public void scheduleSelf(Runnable what, long when) { final Callback callback = getCallback(); if (callback != null) { callback.scheduleDrawable(this, what, when); } } /** * Use the current {@link Callback} implementation to have this Drawable * unscheduled. Does nothing if there is no Callback attached to the * Drawable. * 使用当前Callback的实现去使这个Drawable取消定时。如果没有为Drawable设置Callable, * @param what The runnable that you no longer want called. * * @see Callback#unscheduleDrawable */ public void unscheduleSelf(Runnable what) { final Callback callback = getCallback(); if (callback != null) { callback.unscheduleDrawable(this, what); } } /** * Returns the resolved layout direction for this Drawable. * 返回Drawable的布局方向 * @return One of {@link android.view.View#LAYOUT_DIRECTION_LTR}, * {@link android.view.View#LAYOUT_DIRECTION_RTL} * * @hide */ public int getLayoutDirection() { return mLayoutDirection; } /** * Set the layout direction for this drawable. Should be a resolved direction as the * Drawable as no capacity to do the resolution on his own. * 为Drawable设置布局方向。当Drawable没有能力解决方向问题的时候使用。 * @param layoutDirection One of {@link android.view.View#LAYOUT_DIRECTION_LTR}, * {@link android.view.View#LAYOUT_DIRECTION_RTL} * * @hide */ public void setLayoutDirection(@View.ResolvedLayoutDir int layoutDirection) { if (getLayoutDirection() != layoutDirection) { mLayoutDirection = layoutDirection; } } /** * Specify an alpha value for the drawable. 0 means fully transparent, and * 255 means fully opaque. * 设置透明度。0表示完全透明,255表示完全不透明。 */ public abstract void setAlpha(int alpha); /** * Gets the current alpha value for the drawable. 0 means fully transparent, * 255 means fully opaque. This method is implemented by * Drawable subclasses and the value returned is specific to how that class treats alpha. * The default return value is 255 if the class does not override this method to return a value * specific to its use of alpha. * 获得当前透明度。这个方法被Drawable的子类使用并且返回值和子类怎么处理透明度有关。 * 默认返回255如果子类没有重载这个方法。 */ public int getAlpha() { return 0xFF; } /** * @hide Consider for future API inclusion * 未来的API */ public void setXfermode(Xfermode mode) { // Base implementation drops it on the floor for compatibility. Whee! // TODO: For this to be included in the API proper, all framework drawables need impls. // For right now only BitmapDrawable has it. } /** * Specify an optional color filter for the drawable. Pass {@code null} to * remove any existing color filter. * 指定一个颜色过滤器。传入null可以移除当前所有的过滤器。 * @param cf the color filter to apply, or {@code null} to remove the * existing color filter */ public abstract void setColorFilter(ColorFilter cf); /** * Specify a color and Porter-Duff mode to be the color filter for this * drawable. * 为过滤器设置颜色和波特达夫模式 */ public void setColorFilter(int color, PorterDuff.Mode mode) { setColorFilter(new PorterDuffColorFilter(color, mode)); } /** * Specifies a tint for this drawable. * <p> * Setting a color filter via {@link #setColorFilter(ColorFilter)} overrides * tint. * 设置明调。 * @param tint Color to use for tinting this drawable * @see #setTintMode(PorterDuff.Mode) */ public void setTint(int tint) { setTintList(ColorStateList.valueOf(tint)); } /** * Specifies a tint for this drawable as a color state list. * <p> * Setting a color filter via {@link #setColorFilter(ColorFilter)} overrides * tint. * 通过一个color state list设置明调 * @param tint Color state list to use for tinting this drawable, or null to * clear the tint * @see #setTintMode(PorterDuff.Mode) */ public void setTintList(ColorStateList tint) {} /** * Specifies a tint blending mode for this drawable. * <p> * Setting a color filter via {@link #setColorFilter(ColorFilter)} overrides * tint. * 设置色彩混合模式 * @param tintMode Color state list to use for tinting this drawable, or null to * clear the tint * @param tintMode A Porter-Duff blending mode */ public void setTintMode(PorterDuff.Mode tintMode) {} /** * Returns the current color filter, or {@code null} if none set. * 获得当前颜色过滤器 * @return the current color filter, or {@code null} if none set */ public ColorFilter getColorFilter() { return null; } /** * Removes the color filter for this drawable. * 清楚颜色过滤器 */ public void clearColorFilter() { setColorFilter(null); } /** * Specifies the hotspot's location within the drawable. * 在drawable中指定热区 * @param x The X coordinate of the center of the hotspot * @param y The Y coordinate of the center of the hotspot */ public void setHotspot(float x, float y) {} /** * Sets the bounds to which the hotspot is constrained, if they should be * different from the drawable bounds. * 如果热区的边界要和drawable的边界不同,那么设置边界 * @param left * @param top * @param right * @param bottom */ public void setHotspotBounds(int left, int top, int right, int bottom) {} /** @hide For internal use only. Individual results may vary. */ public void getHotspotBounds(Rect outRect) { outRect.set(getBounds()); } /** * Whether this drawable requests projection. * 是否需要投影 * @hide magic! */ public boolean isProjected() { return false; } /** * Indicates whether this drawable will change its appearance based on * state. Clients can use this to determine whether it is necessary to * calculate their state and call setState. * Drawable是否会根据状态改变外观。使用者可以以此决定是否需要去计算它们的状态和 * 设置状态 * @return True if this drawable changes its appearance based on state, * false otherwise. * @see #setState(int[]) */ public boolean isStateful() { return false; } /** * Specify a set of states for the drawable. These are use-case specific, * so see the relevant documentation. As an example, the background for * widgets like Button understand the following states: * [{@link android.R.attr#state_focused}, * {@link android.R.attr#state_pressed}]. * 为drawable设置一系列状态。有一些特殊的使用例子可以看相关文档。例如,Button之类的 * 控件背景,有以下状态focused,pressed * * <p>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, <em>and</em> * true will be returned from this function. * 如果你使用的新状态会导致外观变化,那么主动调用nvalidateSelf引起重绘并且该方法将返回true * <p>Note: The Drawable holds a reference on to <var>stateSet</var> * until a new state array is given to it, so you must not modify this * array during that time.</p> * Drawable持有stateSet的引用直到赋给它一个新的状态数组,所以你必须在这段时间修改数组 * @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. * 如果drwaable在状态之间有属性动画,调用这个方法立刻跳到当前状态,跳过所有动画 */ 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. * 返回当前被使用的drawale.对于简单的drawable,会返回本身。对于改变状态的drawable,会返回当前使用的子drawable */ 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. * 指定当前层。这允许drawable根据连续的控制者改变自己的图像,例如进度和音量水平。 * <p>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, <em>and</em> * true will be returned from this function. * 如果你使用的新层会导致外观变化,那么主动调用nvalidateSelf引起重绘并且该方法将返回true * @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. * 设置是否可见。一般不会影响drawable的行为。但是可以被一些drawable作为依据,例如决定 * 是否运行动画 * @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. * 你可以设置为true强制drawable表现得就像刚可见一样,即使它持续了一段 * 时间才被设置为可见,例如强制动画重新启动。 * * @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}. * 设置Drawable是否自动映像当它的布局方向被设置为从右到左 * @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}. * 返回Drawable是否自动映像当它的布局方向被设置为从右到左 * @return boolean Returns true if this Drawable will be automatically mirrored. */ public boolean isAutoMirrored() { return false; } /** * Applies the specified theme to this Drawable and its children. * 为Drawable和它的孩子设置主题 */ public void applyTheme(@SuppressWarnings("unused") Theme t) { } public boolean canApplyTheme() { 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}. * 返回透明度或者不透明度。返回值是以下格式的常量 * <p>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. * 保守地返回值。例如如果有多个子drawable,并且一次只显示一个,如果其中一个是TRANSLUCENT, * 而其他是OPAQUE,你应该返回TRANSLUCENT。你可以用resolveOpacity()老判断两个不透明度 * 哪个是合理的. * <p>Note that the returned value does <em>not</em> take into account a * custom alpha or color filter that has been applied by the client through * the {@link #setAlpha} or {@link #setColorFilter} methods. * 注意,返回值没有考虑alpha或者color filter * @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. * 从两个不透明度中返回一个合理的。 * <p>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. * 返回Drawable中完全透明的部分。这个可在绘制操作时使用,分辨哪些部分是不会改变的。默认实现 * 返回null,表明没有透明区域。子类可以有选择地复写从而返回确切区域,如果它希望提供这些优化信息的话。 * 但是不是要求它们都这样做。 * @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. * 返回底层drawable对象的固有宽度。如果没有固有宽度返回-1,例如只有纯色。 */ 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. * 返回底层drawable对象的固有高度。如果没有固有宽度返回-1,例如只有纯色。 */ 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. * 返回该Drawable建议的最小宽度。如果一个view使用这个drawable作为背景,它建议View至少 * 使用这个宽度(有些情景下这是不可能的)。这个值不包含任何的内边距。 * @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. * 返回该Drawable建议的最小高度。如果一个view使用这个drawable作为背景,它建议View至少 * 使用这个高度(有些情景下这是不可能的)。这个值不包含任何的内边距。 * @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). * 返回为那些被放置在drawable边界里面的插入物设置的内边距。走向Drawable中心的正值。 * @return true if this drawable actually has a padding, else false. When false is returned, * the padding is always set to 0. */ public boolean getPadding(@NonNull 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. * 返回Drawable在布局时的对准操作使用的插入物 * @hide */ public Insets getOpticalInsets() { return Insets.NONE; } /** * Called to get the drawable to populate the Outline that defines its drawing area. * <p> * This method is called by the default {@link android.view.ViewOutlineProvider} to define * the outline of the View. * <p> * The default behavior defines the outline to be the bounding rectangle of 0 alpha. * Subclasses that wish to convey a different shape or alpha value must override this method. * 调用这个方法去填充决定绘制区域的框架。 * 这个方法默认被ViewOutlineProvider调用,用于决定View的框架。 * 默认设置框架为0透明度的边界矩形。希望传递不同形状或者透明度的子类,必须复写这个方法。 * @see android.view.View#setOutlineProvider(android.view.ViewOutlineProvider) */ public void getOutline(@NonNull Outline outline) { outline.setRect(getBounds()); outline.setAlpha(0); } /** * 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. * 使drawable易变。这个操作没有逆操作。一个易变的drawable保证不和其他drawable共享它的 * 状态。当你需要修改那些从资源加载的drawable的属性时,显得特别有用。所以从相同的资源加载 * 的drawable默认共享一个相同的状态。如果你修改其中一个,所有的其他对象会受到相同的而修改。 * 调用这个方法使其他不会受到影响。 * * @return This drawable. * @see ConstantState * @see #getConstantState() */ public Drawable mutate() { return this; } /** * Clears the mutated state, allowing this drawable to be cached and * mutated again. * <p> * This is hidden because only framework drawables can be cached, so * custom drawables don't need to support constant state, mutate(), or * clearMutated(). * 清除异变状态,允许drawable被缓存并且再次易变。这是个隐藏方法,因为只有frameword * drawable可以被缓存,所有一般的drawable不需要支持这个状态。 * @hide */ public void clearMutated() { // Default implementation is no-op. } /** * Create a drawable from an inputstream * 从输入流中创建drawable */ 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); } finally { Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); } } /** * Create a drawable from an inputstream, using the given resources and * value to determine density information. * 从输入流中创建drawable,使用给定的资源是值去决定密度信息。 */ 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. * 从输入流中创建drawable,使用给定的资源是值去决定密度信息。 */ 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. 解析流协议是我们已经在pad rect中配置的,但是如果bitmap没有ninepatch块, pad会被忽略。如果我们可以改变这个去设置rect,我们可以避免。。。(不会翻) */ 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. /** * 兼容方式:如果目标密度和设备密度不同,但是资源密度和设备密度相同,就不会缩放它 * 使之适用目标密度。这允许我们在兼容模式下,去加载系统的正确密度资源进app,不需 * 要去缩放它们到兼容密度,只是当它们被绘制到屏幕上时,缩放。 */ 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; } final Rect opticalInsets = new Rect(); bm.getOpticalInsets(opticalInsets); return drawableFromBitmap(res, bm, np, pad, opticalInsets, srcName); } return null; } /** * Create a drawable from an XML document. For more information on how to * create resources in XML, see * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>. * 从xml文件中返回drawable. */ public static Drawable createFromXml(Resources r, XmlPullParser parser) throws XmlPullParserException, IOException { return createFromXml(r, parser, null); } /** * Create a drawable from an XML document using an optional {@link Theme}. * For more information on how to create resources in XML, see * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>. * 适用特定的主题从xml文件返回drawable */ public static Drawable createFromXml(Resources r, XmlPullParser parser, Theme theme) 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, theme); 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. * 从xml文件中返回drawable.调用在xml中的parser,尝试从这些标志中创建drawable. * 返回null如果tag不是一个有效的drawable. */ public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs) throws XmlPullParserException, IOException { return createFromXmlInner(r, parser, attrs, null); } /** * Create a drawable from inside an XML document using an optional * {@link Theme}. Called on a parser positioned at a tag in an XML * document, tries to create a Drawable from that tag. Returns {@code null} * if the tag is not a valid drawable. * 适用特定的主题从xml文件返回drawable.调用在xml中的parser,尝试从这些标志中创建drawable. * 返回null如果tag不是一个有效的drawable. */ public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme) throws XmlPullParserException, IOException { final Drawable drawable; final String name = parser.getName(); switch (name) { case "selector": drawable = new StateListDrawable(); break; case "animated-selector": drawable = new AnimatedStateListDrawable(); break; case "level-list": drawable = new LevelListDrawable(); break; case "layer-list": drawable = new LayerDrawable(); break; case "transition": drawable = new TransitionDrawable(); break; case "ripple": drawable = new RippleDrawable(); break; case "color": drawable = new ColorDrawable(); break; case "shape": drawable = new GradientDrawable(); break; case "vector": drawable = new VectorDrawable(); break; case "animated-vector": drawable = new AnimatedVectorDrawable(); break; case "scale": drawable = new ScaleDrawable(); break; case "clip": drawable = new ClipDrawable(); break; case "rotate": drawable = new RotateDrawable(); break; case "animated-rotate": drawable = new AnimatedRotateDrawable(); break; case "animation-list": drawable = new AnimationDrawable(); break; case "inset": drawable = new InsetDrawable(); break; case "bitmap": drawable = new BitmapDrawable(r); if (r != null) { ((BitmapDrawable) drawable).setTargetDensity(r.getDisplayMetrics()); } break; case "nine-patch": drawable = new NinePatchDrawable(); if (r != null) { ((NinePatchDrawable) drawable).setTargetDensity(r.getDisplayMetrics()); } break; default: throw new XmlPullParserException(parser.getPositionDescription() + ": invalid drawable tag " + name); } drawable.inflate(r, parser, attrs, theme); return drawable; } /** * Create a drawable from file path name. * 从文件路径中创建drawable */ 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. Does not apply a theme. * 从xml资源找到drwale,没有使用主题 * @see #inflate(Resources, XmlPullParser, AttributeSet, Theme) */ public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) throws XmlPullParserException, IOException { inflate(r, parser, attrs, null); } /** * Inflate this Drawable from an XML resource optionally styled by a theme. * 从xml资源找到drwale,使用主题指定的样式 * @param r Resources used to resolve attribute values * @param parser XML parser from which to inflate this Drawable * @param attrs Base set of attribute values * @param theme Theme to apply, may be null * @throws XmlPullParserException * @throws IOException */ public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme) throws XmlPullParserException, IOException { final TypedArray a; if (theme != null) { a = theme.obtainStyledAttributes( attrs, com.android.internal.R.styleable.Drawable, 0, 0); } else { 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. * 从xml资源找到drwale * @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. * 这个抽象类被drawable用于在drawable之间存储共享的常量状态和数据。从同一资源创建的BitmapDrawable将会 * 共享一个唯一的存储在ConstantState中的bitmap * <p> * {@link #newDrawable(Resources)} can be used as a factory to create new Drawable instances * from this ConstantState. * newDrawable()方法可以当成工厂去从ConstantState创建一个新的Drawable * </p> * * 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. * 使用getConstantState()获取drawable的ConstantState。在Drawable调用#mutate()会为这个drawable创建一个 * 新的ConstantState */ 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. * 创建drawable,不需要调用者提供资源。注意,使用它意味着依赖密度的drawables例如(bitmaps) * 将不能正确更新它们的目标密度。应该使用newDrawable(Resources res)而不是提供一个资源。 */ 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). * 从常状态中创建一个新的drawable对象。这个必须被那些变化依赖于目标状态密度的调用者 * 实现。 */ public Drawable newDrawable(Resources res) { return newDrawable(); } /** * Create a new Drawable instance from its constant state. This must be * implemented for drawables that can have a theme applied. * 从常状态中创建一个新的drawable对象。这个必须被那些有主题的调用者实现。 */ public Drawable newDrawable(Resources res, Theme theme) { return newDrawable(null); } /** * Return a bit mask of configuration changes that will impact * this drawable (and thus require completely reloading it). * 返回会影响drawable的一个bit掩码变化设置。 */ public abstract int getChangingConfigurations(); /** * @return Total pixel count 所有的像素 * @hide */ public int addAtlasableBitmaps(Collection<Bitmap> atlasList) { return 0; } /** @hide */ protected final boolean isAtlasable(Bitmap bitmap) { return bitmap != null && bitmap.getConfig() == Bitmap.Config.ARGB_8888; } /** * Return whether this constant state can have a theme applied. * 返回这个常状态是否可以有主题 */ public boolean canApplyTheme() { return false; } } /** * Return a {@link ConstantState} instance that holds the shared state of this Drawable. * 返回Drawable共享的ConstantState实例 * @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); } /** * Ensures the tint filter is consistent with the current tint color and * mode. * 保证色彩过滤器和当前色彩和色彩模式一致。 */ PorterDuffColorFilter updateTintFilter(PorterDuffColorFilter tintFilter, ColorStateList tint, PorterDuff.Mode tintMode) { if (tint == null || tintMode == null) { return null; } final int color = tint.getColorForState(getState(), Color.TRANSPARENT); if (tintFilter == null) { return new PorterDuffColorFilter(color, tintMode); } tintFilter.setColor(color); tintFilter.setMode(tintMode); return tintFilter; } /** * Obtains styled attributes from the theme, if available, or unstyled * resources if the theme is null. * 如果有效,从主题中取得样式属性。如果主题为空,则返回没有样式的资源。 */ static TypedArray obtainAttributes( Resources res, Theme theme, AttributeSet set, int[] attrs) { if (theme == null) { return res.obtainAttributes(set, attrs); } return theme.obtainStyledAttributes(set, attrs, 0, 0); } /** * Parses a {@link android.graphics.PorterDuff.Mode} from a tintMode * attribute's enum value. * 从tintMode解析出PorterDuff.Mode * @hide */ public static PorterDuff.Mode parseTintMode(int value, Mode defaultMode) { switch (value) { case 3: return Mode.SRC_OVER; case 5: return Mode.SRC_IN; case 9: return Mode.SRC_ATOP; case 14: return Mode.MULTIPLY; case 15: return Mode.SCREEN; case 16: return Mode.ADD; default: return defaultMode; } } }
android.graphics.drawable.Drawable注释翻译
标签:
原文地址:http://blog.csdn.net/crazy__chen/article/details/47374631