《Android 開發藝術探索》筆記9--Andriod影片深入分析
- View影片
- View影片的種類
- 自定義View影片
- 幀影片
- View影片的特殊使用場景
- LayoutAnimation
- Activity的切換效果
- 屬性影片
- 使用屬性影片
- 理解插值器和估值器
- 屬性影片的監聽器
- 對任意屬性做影片
- 屬性影片的作業原理
- 使用影片的注意事項
- 參看文章
View影片
View影片作用的物件是View, 它支持四種影片效果平移, 縮放, 旋轉, 透明. 除了這四種典型的變化效果. 幀影片也屬于View影片.
View影片的種類
View影片的四種變換效果對應著Animation的四個子類:TranslateAnimation, ScaleAnimation, RotateAnimation和AlphaAnimation.
對于View影片建議采用XML來定義影片
| 名稱 | 標簽 | 子類 | 效果 |
|---|---|---|---|
| 平移影片 | <translate> | TranslateAnimation | 移動View |
| 縮放影片 | <scale> | ScaleAnimation | 放大或者縮小View |
| 旋轉影片 | <rotate> | RotateAnimation | 旋轉View |
| 透明度影片 | <alpha> | AlphaAnimation | 改變View的透明度 |
創建的影片的xml檔案. 是放在res/anim這個檔案夾下的. View影片描述檔案的固有語法如下
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"
android:shareInterpolator="true"
android:fillAfter="true">
<alpha
android:fromAlpha="float"
android:toAlpha="float"/>
<scale
android:fromXScale="float"
android:toXScale="float"
android:fromYScale="float"
android:toYScale="float"
android:pivotX="float"
android:pivotY="float"/>
<translate
android:fromXDelta="float"
android:toXDelta="float"
android:fromYDelta="float"
android:toYDelta="float"/>
<rotate
android:fromDegrees="float"
android:toDegrees="float"
android:pivotY="float"
android:pivotX="float"/>
</set>
關于影片我們可以只設定一種也可以設定多種的組合.
set標簽對應著AnimationSet類, 標簽中的屬性的意義:
- shareInterpolator 表示集合中的影片是否和集合共享一個插值器. 如果集合不指定插值器, 那么子影片就需要單獨制定所需的插值器或者使用默認值
- fillAfter 是否保留影片結束之后的狀態
translate標簽表示平移影片, 對應著TranslateAnimation類
屬性值的意義就是from開頭的為開始起點, to開頭的結束點
scale標簽表示縮放影片, 對應著ScaleAnimation類
屬性值的意思from開頭的表示開始時原圖縮放的百分比. 用浮點數表示1表示100%(無變化),0.5表示50%(原來的一般), 2表示200%(原來的兩倍). to開頭的表示結束時的百分比. pivot表示縮放的軸點.
rotate標簽表示旋轉影片, 對應著RotateAnimation類
fromDegrees旋轉的開始角度, toDegrees旋轉的結束角度. pivot旋轉的軸點
alpha標簽表示透明度影片, 對應AlphaAnimation類
fromAlpha表示透明度的起始值, toAlpha表示透明度的結束值.
上面這些標簽還有一些通用的屬性值. 例如duration執行時間.
xml如果宣告了之后那么我們就該在代碼中應用了. 如下:
View btn_main = findViewById(R.id.parent);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.temp);
btn_main.startAnimation(animation);
同樣也可以不需要xml直接在代碼中生成影片物件.
AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
alphaAnimation.setDuration(1000);
btn_main.startAnimation(alphaAnimation);
在開始影片之前可以給影片添加一個監聽setAnimationListener()這樣在影片開始結束和每一次回圈下一次的時候都可以在回呼方法中監聽到.
自定義View影片
如果需要自定義View影片, 首先應該繼承Animation這個抽象類來派生出一種新影片. 然后重寫initialize()和applyTransformation()方法. 在initialize中做一些初始化動作, 在applyTransformation()中進行相應矩陣變換, 很多時候需要采用Camera來簡化矩陣變換的程序. 而View影片變化主要就是矩陣的變換程序.
幀影片
幀影片是順序播放一組預先定義好的圖片, 類似于電影. 系統提供了AnimationDrawable來使用幀影片.
同樣在xml中宣告, 在res/drawable/包下創建檔案, 并替換每個drawable圖片即可
<?xml version="1.0" encoding="utf-8"?>
<animation-list
xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"
android:oneshot="false">
<item android:drawable="@drawable/xx1" android:duration="500"/>
<item android:drawable="@drawable/xx2" android:duration="500"/>
<item android:drawable="@drawable/xx3" android:duration="500"/>
<item android:drawable="@drawable/xx4" android:duration="500"/>
</animation-list>
將上述的Drawable作為View的背景并通過Drawable來播放影片.
AnimationDrawable background = (AnimationDrawable) iv_main.getBackground();background.start();
View影片的特殊使用場景
前面介紹的View影片都是作用在某一個View物件上的. 還可以針對ViewGroup控制其子元素. 或者針對Activity切換的影片.
LayoutAnimation
LayoutAnimation作用于ViewGroup上的. 為ViewGroup指定一個影片, 這樣當它的子元素出場時都會具有這種影片效果. 常用的使用場景是在ListView和GridView. 使用很簡單步驟如下.
- 在
res/anim/檔案夾下創建xml檔案.
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"
android:delay="0.5"
android:animationOrder="random"
android:animation="@anim/layout">
</layoutAnimation>
delay: 子元素開始影片的延遲時間, 傳入值是浮點值. 1為100%. 例如如果是0.5 入場影片周期為300ms(下面關聯影片的duration時間), 那么每個子元素都需要延遲150ms才能播放入場影片. 而且這個時間會根據item的遞增而增加. 比方說第一個為延遲150ms, 第二個就是300ms依次類推.
animationOrder: 子元素影片的順序, 有三種選擇normal,reverse,random. reverse表示排在后面的元素先執行入場影片. random隨機子元素執行影片.
animation: 為子元素指定具體的入場影片. 里面放的就是針對View的animation影片的xml
layoutAnimation宣告完成之后, 在要作用的ViewGroup標簽中增加android:layoutAnimation:"@anim/xxx"進行關聯即可. 同樣也可以通過代碼創建LayoutAnimation類來實作.
//獲得子元素需要執行的View影片
Animation animation = AnimationUtils.loadAnimation(this, R.anim.layout);
//創建一個LayoutAnimation影片物件
LayoutAnimationController controller = new LayoutAnimationController(animation);
controller.setDelay(0.5f);
controller.setOrder(LayoutAnimationController.ORDER_RANDOM);
//對ViewGrop進行系結
listView.setLayoutAnimation(controller);
Activity的切換效果
Activity默認是有一種切換效果的. 如果需要自定義切換效果, 主要用到overridePendingTransition()這個方法, 這個方法必須在startActivity()或者finish()之后呼叫才會生效
需要的形參有兩個, 第一個是被打開時候所需的影片資源id, 第二個是被暫停時,所需的影片資源id.
屬性影片
屬性影片是API新加入的特性, 和View影片不同, 它對作用物件進行了擴展, 屬性影片可以對任何物件做影片. 屬性影片不再像View影片那樣只能支持四種簡單的交換 . 屬性影片中有valueAnimator. ObjectAnimator, AnimatorSet等概念
使用屬性影片
屬性影片可以對任何物件的屬性進行影片而不僅僅是View, 影片默認時間間隔為300ms, 默認幀率10ms/幀. 可以達到的效果為: 在一段時間間隔內完成物件從一個屬性值到另一個屬性值的改變. 屬性影片是從API11增加的.
如: 改變一個物件的背景色屬性, 典型的改變View的背景色, 下面的影片可以讓背景顏色的漸變, 影片會無限回圈而且會有反轉效果.
ObjectAnimator colorAnim = ObjectAnimator.ofInt(activity_main, "backgroundColor", 0xffffa000, 0xffffa0ff);
colorAnim.setDuration(5000);
colorAnim.setEvaluator(new ArgbEvaluator());
colorAnim.setRepeatCount(ValueAnimator.INFINITE);
colorAnim.setRepeatMode(ValueAnimator.REVERSE);
colorAnim.start();
影片集合,5秒內對View旋轉平移縮放透明
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(
ObjectAnimator.ofFloat(iv_main, "rotationX", 0,360),
ObjectAnimator.ofFloat(iv_main, "rotationY", 0,360),
ObjectAnimator.ofFloat(iv_main, "rotation", 0,360),
ObjectAnimator.ofFloat(iv_main, "translationX", 0,200),
ObjectAnimator.ofFloat(iv_main, "translationY", 0,200),
ObjectAnimator.ofFloat(iv_main, "scaleX", 1,1.5f),
ObjectAnimator.ofFloat(iv_main, "scaleY", 1,1.5f),
ObjectAnimator.ofFloat(iv_main, "alpha", 1, 0.25f, 1)
);
animatorSet.setDuration(5*1000).start();
也可以使用xml的形式形式來宣告
理解插值器和估值器
TimeInterpolator時間插值器, 作用是根據時間流逝的百分比來計算當前屬性值改變的百分比. 系統預置的有
LinearInterpolator(線性插值器:勻速影片)AccelerateDecelerateInterpolator(加速減速插值器:影片兩頭慢中間快)DecelerateInterpolator(減速插值器:影片越來越慢)
TypeEvaluator 型別估值演算法, 也叫估值器. 作用是根據當前屬性改變的百分比來計算改變后的屬性值. 系統預置的估值器有
IntEvaluator整形估值器FloatEvaluator浮點型估值器ArgbEvaluatorColor屬性估值器
屬性影片中的插值器和估值器都很重要, 他們是實作非勻速影片的重要手段
屬性影片要求物件的該屬性有set``get方法. 插值器和估值器演算法除了系統提供的外. 也可以自定義. 實作方式也很簡單, 因為插值器和估值演算法都是一個介面, 且內部都只有一個方法, 我們只要派生一個類實作介面接可以. 具體就是: 自定義插值器需要實作Interpolator或者TimeInterpolator. 自定義估值演算法需要實作TypeEvaluator
屬性影片的監聽器
屬性影片提供了監聽器用于監聽影片的播放程序 主要有兩個介面AnimatorUpdateListener和AnimatorListener介面.
AnimatorListener通過介面的定義可以看出, 監聽了影片的開始,結束,取消,以及重復播放. 系統為了方便開發提供了AnimatorListenerAdapter類. 他是AnimatorListener的配接器. 這樣就不需要非得實作四個抽象方法而是按照我們的需要選擇復寫.AnimatorUpdateListener比較特殊, 他會監聽整個影片程序, 影片是由許多幀組成的. 每播放一幀onAnimationUpdate就會被呼叫一次
對任意屬性做影片
問題: 如果需要把一個button控制元件的寬增加200px. 應該怎么做?
View影片只是支持四種基本的屬性操作, 而Scale只是縮放. 并且還會對內容進行拉伸并且伴隨著y軸的增加. 所以屬性影片在這里就可以派上用場. 但是如果直接對width屬性進行修改那么不會有效果. 分析一下:
屬性影片的原理: 屬性影片要求影片作用的物件提供該屬性的get和set方法, 屬性影片根據外界傳遞的該屬性值的初始值和最終值, 以影片的效果多次呼叫set每次set的值也是不同. 最終達到終點值.
所以要讓影片生效應該滿足兩個條件:
- 必須提供
setXXX()方法, 如果影片沒有傳遞初始值還要提供getXXX()方法. 這樣系統在需要初始屬性的時候在取值時不會因為沒有getXXX()而發生Crash. - set修改的值必須能改通過某種形式反映出來, 比如會帶來UI的改變. (如果不滿足這條,影片無效果但不會Crash)
那Button本身具備setWidth()為什么會無效果. 這是因為雖然Button提供了方法, 但是這個setWidth()方法并不是改變視圖大小的, 他是TextView新添加的方法, View卻沒有這樣的方法. 而setWidth()方法的內部,作用不是設定View的大小, 而是設定TextView的最大寬度和最小寬度, 這個和TextView的寬是兩個東西. 這樣說控制元件的寬度對應xml中的layout_width, 而setWidth()對應的就是xml中的width屬性. 所以綜合上述原因, 滿足條件一而不滿足條件二.
官網檔案中給出了三種解決方案:
-
給你的物件加上get和set方法, 如果你有權限的話.
-
用一個類來包裝原始物件, 間接為其提供get和set方法.
-
采用valueAnimator, 監聽影片程序,自己實作屬性的改變.
-
雖然簡單但是沒有權限去SDK內部實作去
-
可以創建一個內部包裝類創建set(),get()方法對View的
LayoutParams.width進行修改. -
采用
ValueAnimator, 監聽影片程序, 自己實作屬性改變.ValueAnimator本身不作用于任何物件. 但是他可以對一個值做影片. 通過對每個值的分配并會回呼函式回傳此值, 可以手動進行實作.
屬性影片的作業原理
前面說過, 說屬性畫要求作用的物件提供該屬性方法set方法, 屬性影片根據傳遞的該屬性的初始值和最終值, 以影片的效果多次去呼叫set方法. 每次set方法時候傳遞的值都是不一樣的. 也就是隨著時間的推移所傳遞的值會越來越接近終點值.
原始碼分析: 針對ObjectAnimator的start()為入口
@Override
public void start() {
// See if any of the current active/pending animators need to be canceled
AnimationHandler handler = sAnimationHandler.get();
if (handler != null) {
int numAnims = handler.mAnimations.size();
for (int i = numAnims - 1; i >= 0; i--) {
if (handler.mAnimations.get(i) instanceof ObjectAnimator) {
ObjectAnimator anim = (ObjectAnimator) handler.mAnimations.get(i);
if (anim.mAutoCancel && hasSameTargetAndProperties(anim)) {
anim.cancel();
}
}
}
numAnims = handler.mPendingAnimations.size();
for (int i = numAnims - 1; i >= 0; i--) {
if (handler.mPendingAnimations.get(i) instanceof ObjectAnimator) {
ObjectAnimator anim = (ObjectAnimator) handler.mPendingAnimations.get(i);
if (anim.mAutoCancel && hasSameTargetAndProperties(anim)) {
anim.cancel();
}
}
}
numAnims = handler.mDelayedAnims.size();
for (int i = numAnims - 1; i >= 0; i--) {
if (handler.mDelayedAnims.get(i) instanceof ObjectAnimator) {
ObjectAnimator anim = (ObjectAnimator) handler.mDelayedAnims.get(i);
if (anim.mAutoCancel && hasSameTargetAndProperties(anim)) {
anim.cancel();
}
}
}
}
if (DBG) {
Log.d(LOG_TAG, "Anim target, duration: " + getTarget() + ", " + getDuration());
for (int i = 0; i < mValues.length; ++i) {
PropertyValuesHolder pvh = mValues[i];
Log.d(LOG_TAG, " Values[" + i + "]: " +
pvh.getPropertyName() + ", " + pvh.mKeyframes.getValue(0) + ", " +
pvh.mKeyframes.getValue(1));
}
}
super.start();
}
這段代碼主要就是取消和當前影片相同的影片. 最開始判斷了當前影片,等待影片,延遲影片是否有一致的. 如果有那么就給取消. 最后呼叫了父類方法. 因為ObjectAnimator繼承了ValueAnimator,所以繼續看一下父類的start()
private void start(boolean playBackwards) {
if (Looper.myLooper() == null) {
throw new AndroidRuntimeException("Animators may only be run on Looper threads");
}
mReversing = playBackwards;
mPlayingBackwards = playBackwards;
int prevPlayingState = mPlayingState;
mPlayingState = STOPPED;
mStarted = true;
mStartedDelay = false;
mPaused = false;
updateScaledDuration(); // in case the scale factor has changed since creation time
AnimationHandler animationHandler = getOrCreateAnimationHandler();
animationHandler.mPendingAnimations.add(this);
if (mStartDelay == 0) {
// This sets the initial value of the animation, prior to actually starting it running
if (prevPlayingState != SEEKED) {
setCurrentPlayTime(0);
}
mPlayingState = STOPPED;
mRunning = true;
notifyStartListeners();
}
animationHandler.start();
}
屬性影片需要運行在有Looper的執行緒中, 最侄訓呼叫AnimationHandler.start()方法. AnimationHandler并不是Handler, 他是一個Runnable. 后面會調到JNI層, 然后JNI層還會調回, 然后run方法會被呼叫, 這個Runable涉及和底層的互動. 略過. 看重點.
ValueAnimator的doAnimationFrame()方法, 內部最后呼叫了animationFrame()方法,而animationFrame()內部呼叫了animateValue()方法
void animateValue(float fraction) {
fraction = mInterpolator.getInterpolation(fraction);
mCurrentFraction = fraction;
int numValues = mValues.length;
for (int i = 0; i < numValues; ++i) {
mValues[i].calculateValue(fraction);
}
if (mUpdateListeners != null) {
int numListeners = mUpdateListeners.size();
for (int i = 0; i < numListeners; ++i) {
mUpdateListeners.get(i).onAnimationUpdate(this);
}
}
}
看到了calculateValue()方法, 這個就是計算每幀影片所對應的屬性的值, 然后看一下set,get方法. 比如之前說的如果沒有初始值, 則呼叫get方法等… 查看PropertyValuesHolder類的setupValue()
private void setupValue(Object target, Keyframe kf) {
if (mProperty != null) {
Object value = convertBack(mProperty.get(target));
kf.setValue(value);
}
if (mGetter == null) {
Class targetClass = target.getClass();
setupGetter(targetClass);
if (mGetter == null) {
// Already logged the error - just return to avoid NPE
return;
}
}
Object value = convertBack(mGetter.invoke(target));
kf.setValue(value);
當影片的下一幀到來的時, setAnimatedValue()方法會將新的屬性值給物件, 呼叫其set()方法.同樣set也是反射呼叫
void setAnimatedValue(Object target) {
if (mProperty != null) {
mProperty.set(target, getAnimatedValue());
}
if (mSetter != null) {
mTmpValueArray[0] = getAnimatedValue();
mSetter.invoke(target, mTmpValueArray);
}
}
使用影片的注意事項
- OOM問題: 在幀影片時候容易發生
- 記憶體泄漏: 如果有無限回圈的屬性影片, 在界面退出的時候一定要停止影片 ,否則activity會無法釋放. 而View影片并不存在此問題.
- 兼容性問題: 主要是3.0以下系統
- View影片問題: 因為是對原始View做的影像效果. 并未真正改變View. 所以在影片完成之后.無法GONE掉. 這個時候呼叫
view.clearAnimation()清除View效果即可 - 不要使用px
- 影片互動. 系統3.0之前無論是屬性影片還是View影片新的位置都無法觸發單擊事件.需要注意
- 硬體加速的使用
參看文章
《Android 開發藝術探索》書集
《Android 開發藝術探索》 07-Andriod影片深入分析
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/76446.html
標籤:其他
