Android Drawable完全解析(一):Drawable源碼分析(上)
Android Drawable完全解析(一):Drawable源碼分析(中)
Android Drawable完全解析(一):Drawable源碼分析(下)
呃...我不是故意要湊篇幅寫個(gè)什么上下篇敏弃,實(shí)在是因?yàn)镈rawable源碼有點(diǎn)長,一篇寫不下啦O(∩_∩)O~
上一篇文章 其實(shí)你不懂:Drawable著色(tint)的兼容方案 源碼解析 描述了Drawable的著色原理瓶颠,文章里有涉及到Drawable的一些方法粹淋,順便看一下Drawabld的源碼,發(fā)現(xiàn)Drawable涉及的面很廣借杰,尤其是竟然有那么多的繼承類蔗衡。想想自己平時(shí)也就用過ColorDrawable,StateListDrawable,BitmapDrawable很有限的幾個(gè)子類粘都,對于Drawable的應(yīng)用還是太零散了,所以寫這個(gè)Drawable系列文章堆生,對其做一個(gè)相對完整的分析淑仆!
這是“Drawable完全解析”系列文章的第一篇墩弯,就從Drawable的源碼分析開始渔工!
1:Drawable與其子類的繼承關(guān)系
直接看圖引矩,暫不詳細(xì)介紹具體使用方法。
可以看到Drawable竟然有這么多子類区端,真的需要花一些時(shí)間才能分別搞得清楚。
2:Drawable源碼分析/翻譯
此處源碼是SDK 24版本下的Drawable.java文件,不同版本下應(yīng)該會(huì)有出入延旧,敬請注意!
源碼較長集畅,英文較好的同學(xué)記得指出我翻譯和理解的錯(cuò)誤挺智!
package android.graphics.drawable;
import com.android.internal.R;
*****略
/**
Drawable是一個(gè)用于處理各種可繪制資源的抽象類二鳄。我們使用Drawable最常見的情況就是將獲取到的資源繪制到屏幕上订讼;Drawable類提供了一些通用的API來處理以下具有多種表現(xiàn)形式的可視資源/視覺資源。
* 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.
和View不同脖苏,Drawable實(shí)例不具備任何能力接收事件或與用戶交互。
* Unlike a {@link android.view.View}, a Drawable does not have any facility to
* receive events or otherwise interact with the user.
*
除了簡單繪圖蜒谤,Drawable提供了一些通用的機(jī)制使客戶端與當(dāng)前正在繪制的內(nèi)容進(jìn)行交互。
* <p>In addition to simple drawing, Drawable provides a number of generic
* mechanisms for its client to interact with what is being drawn:
*
setBounds方法必須被Drawable實(shí)例調(diào)用阶祭,用于聲明Drawable實(shí)例繪制的位置和大小濒募。所有的Drawable實(shí)例都會(huì)生成請求的尺寸,這一點(diǎn)通成我Γ可以通過縮放圖像很容易就達(dá)到。對一些Drawable實(shí)例宝磨,客戶端可以通過調(diào)用getIntrinsicHeight和getIntrinsicWidth方法得到其首選尺寸懊烤。
* <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.
getPadding會(huì)將Drawable實(shí)例與實(shí)例中內(nèi)容的間隔信息存儲在Rect實(shí)例中茸习。
* <li> The {@link #getPadding} method can return from some Drawables
* information about how to frame content that is placed inside of them.
例如,一個(gè)Drawable實(shí)例作為一個(gè)Button的背景猫胁,Button控件實(shí)例需要返回padding值用來放置Button控件顯示的內(nèi)容。
* 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.
*
setState方法允許客戶端告知Drawable實(shí)例在什么狀態(tài)下才進(jìn)行繪制菠赚。
例如“焦點(diǎn)獲取狀態(tài)”,“選中狀態(tài)”等等拌牲。某些Drawable可能會(huì)根據(jù)選定的狀態(tài)值變更它們的外觀。
* <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.
*
setLevel方法允許客戶端提供一個(gè)單一的連續(xù)控制器來編輯正在顯示的Drawable實(shí)例砚婆,例如電量水平或者進(jìn)度值坷虑。某些Drawable實(shí)例可以根據(jù)當(dāng)前的level值變更它們的外觀迄损。
* <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.
*
通過Callback接口痊远,一個(gè)Drawable實(shí)例可以回調(diào)其客戶端來執(zhí)行動(dòng)畫冒版。為了動(dòng)畫可以被執(zhí)行辞嗡,所有的客戶端都應(yīng)該支持這個(gè)Callback接口。實(shí)現(xiàn)這一效果最簡單的方法就是通過系統(tǒng)提供的機(jī)制挺狰,例如ImageView,View.setBackgoound方法趁耗。
* <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>
*
盡管通常情況下對應(yīng)用不可見,Drawable實(shí)例可能存在以下多種形式:
Bitmap:最簡單的Drawable形式罢屈,PNG或者JPEG圖片。
.9圖:PNG的一個(gè)擴(kuò)展曼月,可以支持設(shè)置其如何填充內(nèi)容,如何被拉伸聪姿。
Shape:包含簡單的繪制指令破喻,用于替代bitmap,某些情況下對大小調(diào)整有更好表現(xiàn)咆繁。
Layers:一個(gè)復(fù)合的Drawable,按照層級進(jìn)行繪制坏为,單個(gè)Drawable實(shí)例繪制于其下層Drawable實(shí)例集合之上。
States:一個(gè)復(fù)合的Drawable够颠,根據(jù)它的state選擇一個(gè)Drawable集合。
Levels:一個(gè)復(fù)合的Drawable剃诅,根據(jù)它的level選擇一個(gè)Drawable集合。
Scale:一個(gè)復(fù)合的Drawable和單個(gè)Drawable實(shí)例構(gòu)成聊品,它的總體尺寸由它的當(dāng)前l(fā)evel值決定。
* 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>
*
自定義Drawable
所有的Android版本都支持框架層提供的Drawable類被擴(kuò)展/自定義和應(yīng)用于運(yùn)行時(shí)。從Android版本24開始赚抡,自定義Drawable可以在XML中直接使用。
* <a name="Custom"></a>
* <h3>Custom drawables</h3>
*
* <p>
* All versions of Android allow the Drawable class to be extended and used at
* run time in place of framework-provided drawable classes. Starting in
* {@link android.os.Build.VERSION_CODES#N API 24}, custom drawables classes
* may also be used in XML.
* <p>
注:
自定義Drawable僅能應(yīng)用于當(dāng)前應(yīng)用,其他應(yīng)用無法加載它們。
自定義Drawable必須繼承Drawable類剖煌,至少重寫draw方法以繪制內(nèi)容。
* <strong>Note:</strong> Custom drawable classes are only accessible from
* within your application package. Other applications will not be able to load
* them.
* <p>
* At a minimum, custom drawable classes must implement the abstract methods on
* Drawable and should override the {@link Drawable#draw(Canvas)} method to
* draw content.
自定義Drawable用于XML中有多種方式:
1:直接引用自定義Drawable類名的全稱茉兰,且該類必須為公共頂層類。
2:使用drawable作為XML的元素名稱,指定該自定義Drawable類的全稱黔龟。該自定義Drawable類可以是 公共頂層類或者公共靜態(tài)內(nèi)部類。
* <p>
* Custom drawables classes may be used in XML in multiple ways:
* <ul>
* <li>
* Using the fully-qualified class name as the XML element name. For
* this method, the custom drawable class must be a public top-level
* class.
* <pre>
* <com.myapp.MyCustomDrawable xmlns:android="http://schemas.android.com/apk/res/android"
* android:color="#ffff0000" />
* </pre>
* </li>
* <li>
* Using <em>drawable</em> as the XML element name and specifying the
* fully-qualified class name from the <em>class</em> attribute. This
* method may be used for both public top-level classes and public
* static inner classes.
* <pre>
* <drawable xmlns:android="http://schemas.android.com/apk/res/android"
* class="com.myapp.MyTopLevelClass$InnerCustomDrawable"
* android:color="#ffff0000" />
* </pre>
* </li>
* </ul>
*
略
*/
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 @Config 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;
/**
在通過setBounds設(shè)置的范圍內(nèi)進(jìn)行繪制如贷,通過調(diào)用setAlpha和setColorFilter
等方法可以影響繪制的效果。
canvas:當(dāng)前Drawable實(shí)例要被繪制到canvas上。
* 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(@NonNull Canvas canvas);
/**
為當(dāng)前Drawable實(shí)例設(shè)置一個(gè)矩形范圍,在draw方法調(diào)用時(shí)候踪少,
Drawable實(shí)例將被繪制到這個(gè)矩形范圍內(nèi)。
* Specify a bounding rectangle for the Drawable. This is where the drawable
* will draw when its draw() method is called.
*/
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);
}
}
public void setBounds(@NonNull Rect bounds) {
setBounds(bounds.left, bounds.top, bounds.right, bounds.bottom);
}
/**
將當(dāng)前Drawable實(shí)例通過setBounds設(shè)置的繪制范圍拷貝到客戶端提供的Rect實(shí)例中返回
* 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.
*
* @param bounds Rect to receive the drawable's bounds (allocated by the
* caller).
*/
public final void copyBounds(@NonNull Rect bounds) {
bounds.set(mBounds);
}
public final Rect copyBounds() {
return new Rect(mBounds);
}
/**
返回當(dāng)前Drawable實(shí)例的矩形繪制范圍锉罐。注:返回的矩形就是
當(dāng)前Drawable實(shí)際的繪制范圍矩形脓规,所以如果是需要一個(gè)拷貝的矩形范圍秒紧,
應(yīng)該調(diào)用copyBounds來代替。
調(diào)用getBounds叙淌,你不能修改返回的矩形,會(huì)影響Drawable實(shí)例。
* 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.
*
* @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)
*/
@NonNull
public final Rect getBounds() {
if (mBounds == ZERO_BOUNDS_RECT) {
mBounds = new Rect();
}
return mBounds;
}
/**
返回當(dāng)前Drawable實(shí)例的模糊繪制范圍矩形督勺。
注:返回的矩形和當(dāng)前Drawable繪制返回矩形是同一個(gè)對象渠羞。
* 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.
*
* @return The dirty bounds of this drawable
*/
@NonNull
public Rect getDirtyBounds() {
return getBounds();
}
/**
這段我沒怎么看懂,勉強(qiáng)翻譯一下玷氏,哪位同學(xué)懂可以留言堵未!
為配置參數(shù)設(shè)置一個(gè)標(biāo)記,當(dāng)該配置參數(shù)變更時(shí)可能改變當(dāng)前
Drawable實(shí)例盏触,要求當(dāng)前Drawable實(shí)例重新創(chuàng)建块饺。
* 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(@Config int configs) {
mChangingConfigurations = configs;
}
public @Config int getChangingConfigurations() {
return mChangingConfigurations;
}
/**
當(dāng)設(shè)置為true赞辩,該Drawable實(shí)例在繪制到一個(gè)低于8-bits每單位色值
的設(shè)備上時(shí)候顏色將發(fā)生‘抖動(dòng)’?
* Set to true to have the drawable dither its colors when drawn to a
* device with fewer than 8-bits per color component.
*
* @see android.graphics.Paint#setDither(boolean);
* @deprecated This property is ignored.
*/
@Deprecated
public void setDither(boolean dither) {}
/**
當(dāng)設(shè)置為true,則該Drawable實(shí)例在縮放或者旋轉(zhuǎn)時(shí)候?qū)? 對它關(guān)聯(lián)的bitmap進(jìn)行濾波過濾授艰”嫠裕可以提升旋轉(zhuǎn)時(shí)的繪制效果。
如果該Drawable實(shí)例未使用bitmap,這個(gè)方法無作用淮腾。
* Set to true to have the drawable filter its bitmaps with bilinear
* sampling when they are scaled or rotated.
*
* <p>This can improve appearance when bitmaps are rotated. If the drawable
* does not use bitmaps, this call is ignored.</p>
*
* @see #isFilterBitmap()
* @see android.graphics.Paint#setFilterBitmap(boolean);
*/
public void setFilterBitmap(boolean filter) {}
public boolean isFilterBitmap() {
return false;
}
/**
一個(gè)回調(diào)接口糟需,用于調(diào)度和執(zhí)行Drawable實(shí)例的動(dòng)畫。
如果要實(shí)現(xiàn)自定義的動(dòng)畫Drawable,就需要實(shí)現(xiàn)這個(gè)接口谷朝。
* 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.
*/
public interface Callback {
/**
Drawable實(shí)例被重繪時(shí)候調(diào)用洲押。在當(dāng)前Drawable實(shí)例位置的View
實(shí)例需要重繪,或者至少部分重繪圆凰。
* 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).
*
* @param who The drawable that is requesting the update.
*/
void invalidateDrawable(@NonNull Drawable who);
/**
一個(gè)Drawable實(shí)例可以調(diào)用這個(gè)方法預(yù)先安排動(dòng)畫的下一幀杈帐。
也可以通過Handler.postAtTime實(shí)現(xiàn)。
* 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.
*
* @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}
*/
void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when);
/**
一個(gè)Drawable實(shí)例可以調(diào)用這個(gè)方法取消之前安排的某一幀专钉。
也可以通過Handler.removeCallbacks實(shí)現(xiàn)挑童。
* 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.
*
* @param who The drawable being unscheduled.
* @param what The action being unscheduled.
*/
void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what);
}
/**
如果客戶端要求支持動(dòng)畫Drawable,將一個(gè)Callback實(shí)例綁定到當(dāng)前
Drawable實(shí)例上。
* Bind a {@link Callback} object to this Drawable. Required for clients
* that want to support animated drawables.
*
* @param cb The client's Callback implementation.
*
* @see #getCallback()
*/
public final void setCallback(@Nullable Callback cb) {
mCallback = cb != null ? new WeakReference<>(cb) : null;
}
public Callback getCallback() {
return mCallback != null ? mCallback.get() : null;
}
/**
通過由調(diào)用setCallBack設(shè)置過的Callback實(shí)例執(zhí)行
invalidateDrawable跃须。如果沒有調(diào)用過setCallback站叼,則無效果
* Use the current {@link Callback} implementation to have this Drawable
* redrawn. Does nothing if there is no Callback attached to the
* Drawable.
*
* @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);
}
}
/**
通過由調(diào)用setCallBack設(shè)置過的Callback實(shí)例執(zhí)行
scheduleDrawable。如果沒有調(diào)用過setCallback菇民,則無效果
* Use the current {@link Callback} implementation to have this Drawable
* scheduled. Does nothing if there is no Callback attached to the
* Drawable.
*
* @param what The action being scheduled.
* @param when The time (in milliseconds) to run.
*
* @see Callback#scheduleDrawable
*/
public void scheduleSelf(@NonNull Runnable what, long when) {
final Callback callback = getCallback();
if (callback != null) {
callback.scheduleDrawable(this, what, when);
}
}
/**
通過由調(diào)用setCallBack設(shè)置過的Callback實(shí)例執(zhí)行
unscheduleDrawable尽楔。如果沒有調(diào)用過setCallback,則無效果
* Use the current {@link Callback} implementation to have this Drawable
* unscheduled. Does nothing if there is no Callback attached to the
* Drawable.
*
* @param what The runnable that you no longer want called.
*
* @see Callback#unscheduleDrawable
*/
public void unscheduleSelf(@NonNull Runnable what) {
final Callback callback = getCallback();
if (callback != null) {
callback.unscheduleDrawable(this, what);
}
}
/**
獲取當(dāng)前Drawable實(shí)例的布局方向玉雾。
* Returns the resolved layout direction for this Drawable.
*
* @return One of {@link android.view.View#LAYOUT_DIRECTION_LTR},
* {@link android.view.View#LAYOUT_DIRECTION_RTL}
* @see #setLayoutDirection(int)
*/
public @View.ResolvedLayoutDir int getLayoutDirection() {
return mLayoutDirection;
}
/**
設(shè)置當(dāng)前Drawable實(shí)例的布局方向翔试。
* Set the layout direction for this drawable. Should be a resolved
* layout direction, as the Drawable has no capacity to do the resolution on
* its own.
*
* @param layoutDirection the resolved layout direction for the drawable,
* either {@link android.view.View#LAYOUT_DIRECTION_LTR}
* or {@link android.view.View#LAYOUT_DIRECTION_RTL}
* @return {@code true} if the layout direction change has caused the
* appearance of the drawable to change such that it needs to be
* re-drawn, {@code false} otherwise
* @see #getLayoutDirection()
*/
public final boolean setLayoutDirection(@View.ResolvedLayoutDir int layoutDirection) {
if (mLayoutDirection != layoutDirection) {
//如果當(dāng)前Drawable布局方向和layoutDirection不一致,
//則修改布局方向?yàn)閘ayoutDirection复旬,然后執(zhí)行onLayoutDirectionChanged
mLayoutDirection = layoutDirection;
return onLayoutDirectionChanged(layoutDirection);
}
return false;
}
/**
當(dāng)調(diào)用setLayoutDirection方法垦缅,Drawable布局方向發(fā)生變化后調(diào)用
* Called when the drawable's resolved layout direction changes.
*
* @param layoutDirection the new resolved layout direction
* @return {@code true} if the layout direction change has caused the
* appearance of the drawable to change such that it needs to be
* re-drawn, {@code false} otherwise
* @see #setLayoutDirection(int)
*/
public boolean onLayoutDirectionChanged(@View.ResolvedLayoutDir int layoutDirection) {
return false;
}
/**
設(shè)置Drawable實(shí)例的透明度。
0:完全透明
255:完全不透明
* Specify an alpha value for the drawable. 0 means fully transparent, and
* 255 means fully opaque.
*/
public abstract void setAlpha(@IntRange(from=0,to=255) int alpha);
@IntRange(from=0,to=255)
public int getAlpha() {
return 0xFF;
}
/**
被隱匿
* @hide
*
* Internal-only method for setting xfermode on certain supported drawables.
*
* Should not be made public since the layers and drawing area with which
* Drawables draw is private implementation detail, and not something apps
* should rely upon.
*/
public void setXfermode(@Nullable Xfermode mode) {
// Base implementation drops it on the floor for compatibility. Whee!
}
/**
為當(dāng)前Drawable實(shí)例設(shè)置顏色濾鏡
* Specify an optional color filter for the drawable.
* <p>
* If a Drawable has a ColorFilter, each output pixel of the Drawable's
* drawing contents will be modified by the color filter before it is
* blended onto the render target of a Canvas.
* </p>
* <p>
* Pass {@code null} to remove any existing color filter.
* </p>
* <p class="note"><strong>Note:</strong> Setting a non-{@code null} color
* filter disables {@link #setTintList(ColorStateList) tint}.
* </p>
*
* @param colorFilter The color filter to apply, or {@code null} to remove the
* existing color filter
*/
public abstract void setColorFilter(@Nullable ColorFilter colorFilter);
/**
為當(dāng)前Drawable實(shí)例設(shè)置濾鏡效果
* Specify a color and Porter-Duff mode to be the color filter for this
* drawable.
* <p>
* Convenience for {@link #setColorFilter(ColorFilter)} which constructs a
* {@link PorterDuffColorFilter}.
* </p>
* <p class="note"><strong>Note:</strong> Setting a color filter disables
* {@link #setTintList(ColorStateList) tint}.
* </p>
*/
public void setColorFilter(@ColorInt int color, @NonNull PorterDuff.Mode mode) {
setColorFilter(new PorterDuffColorFilter(color, mode));
}
/**
為當(dāng)前Drawable實(shí)例著色
* Specifies tint color for this drawable.
* <p>
當(dāng)前Drawable實(shí)例的繪制內(nèi)容在被繪制到屏幕上之前將被指定顏色著色
當(dāng)前方法和setColorFilter類似驹碍。
* A Drawable's drawing content will be blended together with its tint
* before it is drawn to the screen. This functions similarly to
* {@link #setColorFilter(int, PorterDuff.Mode)}.
* </p>
* <p>
* To clear the tint, pass {@code null} to
* {@link #setTintList(ColorStateList)}.
* </p>
* <p class="note"><strong>Note:</strong> Setting a color filter via
* {@link #setColorFilter(ColorFilter)} or
* {@link #setColorFilter(int, PorterDuff.Mode)} overrides tint.
* </p>
*
* @param tintColor Color to use for tinting this drawable
* @see #setTintList(ColorStateList)
* @see #setTintMode(PorterDuff.Mode)
*/
public void setTint(@ColorInt int tintColor) {
setTintList(ColorStateList.valueOf(tintColor));
}
/**
根據(jù)ColorStateList對當(dāng)前Drawable實(shí)例進(jìn)行著色
這個(gè)一個(gè)空方法1谙选7不小!在上一篇文章中已經(jīng)指出怔球,Drawabld的子類
實(shí)現(xiàn)了這個(gè)方法嚼酝。
* Specifies tint color for this drawable as a color state list.
* <p>
* A Drawable's drawing content will be blended together with its tint
* before it is drawn to the screen. This functions similarly to
* {@link #setColorFilter(int, PorterDuff.Mode)}.
* </p>
* <p class="note"><strong>Note:</strong> Setting a color filter via
* {@link #setColorFilter(ColorFilter)} or
* {@link #setColorFilter(int, PorterDuff.Mode)} overrides tint.
* </p>
*
* @param tint Color state list to use for tinting this drawable, or
* {@code null} to clear the tint
* @see #setTint(int)
* @see #setTintMode(PorterDuff.Mode)
*/
public void setTintList(@Nullable ColorStateList tint) {}
/**
設(shè)置當(dāng)前Drawable實(shí)例著色的過濾模式
* Specifies a tint blending mode for this drawable.
* <p>
* Defines how this drawable's tint color should be blended into the drawable
* before it is drawn to screen. Default tint mode is {@link PorterDuff.Mode#SRC_IN}.
* </p>
* <p class="note"><strong>Note:</strong> Setting a color filter via
* {@link #setColorFilter(ColorFilter)} or
* {@link #setColorFilter(int, PorterDuff.Mode)} overrides tint.
* </p>
*
* @param tintMode A Porter-Duff blending mode
* @see #setTint(int)
* @see #setTintList(ColorStateList)
*/
public void setTintMode(@NonNull PorterDuff.Mode tintMode) {}
public @Nullable ColorFilter getColorFilter() {
return null;
}
/**
取消當(dāng)前Drawable實(shí)例的濾鏡。
* Removes the color filter for this drawable.
*/
public void clearColorFilter() {
setColorFilter(null);
}
/**
設(shè)置當(dāng)前Drawable實(shí)例熱點(diǎn)區(qū)域的中心點(diǎn)坐標(biāo)
* Specifies the hotspot's location within the 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) {}
/**
設(shè)置當(dāng)前Drawable實(shí)例的熱點(diǎn)區(qū)域的邊界
* Sets the bounds to which the hotspot is constrained, if they should be
* different from the drawable bounds.
*
* @param left position in pixels of the left bound
* @param top position in pixels of the top bound
* @param right position in pixels of the right bound
* @param bottom position in pixels of the bottom bound
* @see #getHotspotBounds(android.graphics.Rect)
*/
public void setHotspotBounds(int left, int top, int right, int bottom) {}
/**
* Populates {@code outRect} with the hotspot bounds.
*
* @param outRect the rect to populate with the hotspot bounds
* @see #setHotspotBounds(int, int, int, int)
*/
public void getHotspotBounds(@NonNull Rect outRect) {
outRect.set(getBounds());
}
/**
被隱匿
* Whether this drawable requests projection.
*
* @hide magic!
*/
public boolean isProjected() {
return false;
}
/**
標(biāo)示當(dāng)前Drawable實(shí)例的外觀是否要根據(jù)state進(jìn)行變更竟坛。
客戶端可以用這個(gè)方法判斷是否有必要計(jì)算state并調(diào)用setState闽巩。
* 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.
*
* @return True if this drawable changes its appearance based on state,
* false otherwise.
* @see #setState(int[])
*/
public boolean isStateful() {
return false;
}
/**
為當(dāng)前Drawable實(shí)例設(shè)置一個(gè)狀態(tài)值集合。當(dāng)現(xiàn)有狀態(tài)和stateSet
不同時(shí)候担汤,觸發(fā)onStateChange(stateSet)方法涎跨。
* 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}].
*
* <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.
*
* <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>
*
* @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(@NonNull 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 @NonNull int[] getState() {
return mStateSet;
}
/**
如果當(dāng)前Drawable實(shí)例在執(zhí)行過渡動(dòng)畫,要求當(dāng)前實(shí)例
立即跳轉(zhuǎn)到當(dāng)前狀態(tài)并跳過任何正在執(zhí)行的動(dòng)畫崭歧。
* 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() {
}
/**
返回當(dāng)前Drawable實(shí)例正在使用的Drawable實(shí)例隅很,
對于一般單個(gè)Drawable,返回值就是自身率碾,對于像StateListDrawable
這樣的復(fù)合Drawable實(shí)例叔营,則返回其持有的一個(gè)子Drawable實(shí)例。
* @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 @NonNull Drawable getCurrent() {
return this;
}
/**
為當(dāng)前Drawable實(shí)例設(shè)置圖像級別所宰,從0到10000绒尊。setLevel使得
Drawable實(shí)例可以通過一個(gè)不斷變化的控制器來變更它的圖像,
例如音量等級或者進(jìn)度歧匈。
* 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.
*
* <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.
*
* @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(@IntRange(from=0,to=10000) int level) {
if (mLevel != level) {
//修改圖像等級為level垒酬,并調(diào)用onLevelChange
mLevel = level;
return onLevelChange(level);
}
return false;
}
/**
* Retrieve the current level.
*
* @return int Current level, from 0 (minimum) to 10000 (maximum).
*/
public final @IntRange(from=0,to=10000) int getLevel() {
return mLevel;
}
~~~~(>_<)~~~~
當(dāng)前文章長度正在接近簡書的限度,請考慮分篇書寫吧
~~~~(>_<)~~~~
/**
設(shè)置當(dāng)前Drawable實(shí)例是否可見件炉,并不會(huì)影響Drawable實(shí)例的行為勘究,
但是可以被某些Drawable來控制是否執(zhí)行動(dòng)畫。
例如:AnimationDrawable可以通過這個(gè)方法啟動(dòng)或者停止動(dòng)畫斟冕,
后續(xù)文章會(huì)有驗(yàn)證口糕。
* 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;
}
/**
設(shè)置當(dāng)前Drawable實(shí)例是不是自動(dòng)被“鏡像”/左右對調(diào)
當(dāng)它的布局模式是從右到左
* 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;
}
/**
為當(dāng)前Drawable實(shí)例和它的子實(shí)例應(yīng)用指定的主題
* Applies the specified theme to this Drawable and its children.
*
* @param t the theme to apply
*/
public void applyTheme(@NonNull @SuppressWarnings("unused") Theme t) {
//空方法,Drawable子類會(huì)做自定義實(shí)現(xiàn)
}
public boolean canApplyTheme() {
return false;
}
/**
返回當(dāng)前Drawable實(shí)例的透明或者不透明磕蛇。返回值是其中之一:
{@link android.graphics.PixelFormat#UNKNOWN}-透明度未知
{@link android.graphics.PixelFormat#TRANSLUCENT}-半透明
{@link android.graphics.PixelFormat#TRANSPARENT}-完全透明
{@link android.graphics.PixelFormat#OPAQUE}-完全不透明
如果Drawable中的內(nèi)容可見性不確定景描,最安全的方案
是返回TRANSLUCENT/半透明
* 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>An OPAQUE drawable is one that draws all all content within its bounds, completely
* covering anything behind the drawable. A TRANSPARENT drawable is one that draws nothing
* within its bounds, allowing everything behind it to show through. A TRANSLUCENT drawable
* is a drawable in any other state, where the drawable will draw some, but not all,
* of the content within its bounds and at least some content behind the drawable will
* be visible. If the visibility of the drawable's contents cannot be determined, the
* safest/best return value is TRANSLUCENT.
*
* <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.
*
* <p>Note that the returned value does not necessarily take into account a
* custom alpha or color filter that has been applied by the client through
* the {@link #setAlpha} or {@link #setColorFilter} methods. Some subclasses,
* such as {@link BitmapDrawable}, {@link ColorDrawable}, and {@link GradientDrawable},
* do account for the value of {@link #setAlpha}, but the general behavior is dependent
* upon the implementation of the subclass.
*
* @return int The opacity class of the Drawable.
*
* @see android.graphics.PixelFormat
*/
public abstract @PixelFormat.Opacity int getOpacity();
/**
根據(jù)兩個(gè)不透明度值,返回合適的值秀撇。
兩個(gè)不透明度值若相等超棺,直接返回;
否則如果兩個(gè)透明度值有至少一個(gè)是UNKNOWN呵燕,返回UNKNOWN棠绘;
否則如果兩個(gè)透明度值有至少一個(gè)是TRANSLUCENT,返回TRANSLUCENT;
否則如果兩個(gè)透明度值有至少一個(gè)是TRANSPARENT氧苍,返回TRANSPARENT夜矗;
否則返回OPAQUE;
* 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 @PixelFormat.Opacity int resolveOpacity(@PixelFormat.Opacity int op1,
@PixelFormat.Opacity 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;
}
/**
返回在當(dāng)前Drawable實(shí)例中完全透明的一個(gè)區(qū)域让虐。
這個(gè)區(qū)域可以用來影響繪制操作紊撕,定義當(dāng)前Drawable實(shí)例的目標(biāo)
在渲染當(dāng)前Drawable實(shí)例時(shí)候哪個(gè)區(qū)域不需要改變。
* 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 @Nullable Region getTransparentRegion() {
return null;
}
/**
如果子類需要根據(jù)state來變更Drawable實(shí)例的外觀赡突,則需要重寫該方法对扶。
如果state的變更引起了Drawable實(shí)例外觀變化,則返回true,
否則返回false;
* 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;
}
/**
如果子類需要根據(jù)level來變更Drawable實(shí)例的外觀惭缰,則需要重寫該方法辩稽。
如果level的變更引起了Drawable實(shí)例外觀變化,則返回true,
否則返回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;
}
/**
如果子類實(shí)例需要在繪制范圍發(fā)生變化后變更Drawable實(shí)例的外觀从媚,則需要重寫該方法。
* Override this in your subclass to change appearance if you vary based on
* the bounds.
*/
protected void onBoundsChange(Rect bounds) {
// Stub method.
}
/**
返回當(dāng)前Drawable實(shí)例的實(shí)質(zhì)寬度患整。
實(shí)質(zhì)寬度是Drawable實(shí)例占據(jù)的寬度拜效,包含padding值。
如果Drawable實(shí)例沒有實(shí)際寬度各谚,例如是一個(gè)顏色紧憾,則返回-1
* Returns the drawable's intrinsic width.
* <p>
* Intrinsic width is the width at which the drawable would like to be laid
* out, including any inherent padding. If the drawable has no intrinsic
* width, such as a solid color, this method returns -1.
*
* @return the intrinsic width, or -1 if no intrinsic width
*/
public int getIntrinsicWidth() {
return -1;
}
/**
返回當(dāng)前Drawable實(shí)例的實(shí)質(zhì)高度。
實(shí)質(zhì)寬度是Drawable實(shí)例占據(jù)的高度昌渤,包含padding值赴穗。
如果Drawable實(shí)例沒有實(shí)際高度,例如是一個(gè)顏色膀息,則返回-1
* Returns the drawable's intrinsic height.
* <p>
* Intrinsic height is the height at which the drawable would like to be
* laid out, including any inherent padding. If the drawable has no
* intrinsic height, such as a solid color, this method returns -1.
*
* @return the intrinsic height, or -1 if no intrinsic height
*/
public int getIntrinsicHeight() {
return -1;
}
/**
返回當(dāng)前Drawable建議的最小寬度般眉。
如果一個(gè)View實(shí)例用當(dāng)前Drawable當(dāng)做背景,那么建議該View實(shí)例
寬度最小為這個(gè)值潜支。
* 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;
}
/**
返回當(dāng)前Drawable建議的最小高度甸赃。
如果一個(gè)View實(shí)例用當(dāng)前Drawable當(dāng)做背景,那么建議該View實(shí)例
高度最小為這個(gè)值冗酿。
* 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;
}
/**
將當(dāng)前Drawable實(shí)例的padding值作為參數(shù)設(shè)置為Recti實(shí)例padding
的邊界值埠对。
如果當(dāng)前實(shí)例有padding值,返回true,否則返回false裁替;
當(dāng)返回false项玛,則Recti實(shí)例padding的邊界值都設(shè)置為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).
*
* @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.
* @hide
*/
public @NonNull Insets getOpticalInsets() {
return Insets.NONE;
}
/**
調(diào)用此方法獲取當(dāng)前Drawable實(shí)例的繪制區(qū)域輪廓弱判。
這個(gè)方法默認(rèn)被ViewOutlineProvider調(diào)用去定義View實(shí)例的輪廓襟沮。
ViewOutlineProvider:后續(xù)文章會(huì)做介紹,是個(gè)蠻有趣的類。
* 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.
*
* @see android.view.View#setOutlineProvider(android.view.ViewOutlineProvider)
*/
public void getOutline(@NonNull Outline outline) {
outline.setRect(getBounds());
outline.setAlpha(0);
}
未完待續(xù)...
未完待續(xù)...
以上就是個(gè)人分析的一點(diǎn)結(jié)果臣嚣,若有錯(cuò)誤净刮,請各位同學(xué)留言告知!
That's all !