作者:湘北南
連結:https://www.jianshu.com/p/8114ed31c535
1、概述
在深入瞭解Apng動畫播放之前,我們需要對Apng的結構有所瞭解,具體參見Apng動畫介紹https://www.jianshu.com/p/5333bcc20ba7,對Apng的整體結構有所瞭解後,下麵我們來講講Apng動畫的播放,主要包括Apng解析和Apng渲染兩個過程。
2、Apng動畫播放流程
Apng動畫播放流程包括Apng解析和Apng渲染兩個過程,Apng解析主要有兩種方法,下麵我們將會介紹,而Apng渲染主要包括三個步驟:消除(dispose)、合成(blend)、繪製(draw),由此得到Apng動畫播放流程圖如下:
3、Apng的解析
Apng的解析主要是將Apng檔案轉化成Apng序列幀Frame-n,從上面的流程圖可知,Apng檔案的解析列出了兩種方案,下麵來分別說說:
1)Apng檔案首先經過一個解壓(ApngExact)的過程,生成png序列幀儲存在本地,然後經過載入(LoadPng)處理生成序列幀Frame-n。
假設Apng動畫檔案總共有90幀,那麼經過ApngExact處理後,會生成90張png序列幀儲存在本地,每幀透過LoadPng處理生成Bitmap並供後面的Apng渲染使用。
2)Apng是一個獨立的檔案,我們自己編寫讀取Apng檔案的程式碼類:ApngReader,當渲染第i幀時,透過ApngReader直接獲取第i幀的Bitmap。
比較:
1)方案一是將Apng檔案全部解壓成png序列圖片儲存在本地,方案二是把Apng檔案當做一個整體去處理,需要第幾幀直接讀取第幾幀,並將該幀以Bitmap的形似儲存到記憶體。
2)方案一解壓得到的png圖片在後面的渲染中需要轉化成Bitamp,而方案二直接就獲取了第幾幀的Bitmap,相比於方案一,方案二減少了一個從SD卡讀取png檔案的操作。
4、Apng的渲染
方案一的具體實現大家可以參考github上面的一個專案apng-view,下麵我們來講講方案二的具體實現,即ApngReader的具體實現。
1) 解析Apng的每一幀
我們是將整個檔案放到一個buffer裡面,並且透過RandomAccessFile、MappedByteBuffer來讀取Apng的每一幀,ApngReader的建構式如下:
public ApngReader(String apngFile) throws IOException, FormatNotSupportException {
RandomAccessFile f = new RandomAccessFile(apngFile, "r");
mBuffer = f.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, f.length());
f.close();
if (mBuffer.getInt() != PNG_SIG
&& mBuffer.getInt(4) != PNG_SIG_VER
&& mBuffer.getInt(8) != CODE_IHDR) {
throw new FormatNotSupportException("Not a png/apng file");
}
mChunk = new ApngMmapParserChunk(mBuffer);
reset();
}
下麵來看看讀取每一幀的方法:
/**
* get next frame control info & bitmap
*
* @return next frame control info, or null if no next FCTL chunk || no next IDAT/FDAT
* @throws IOException
*/
public ApngFrame nextFrame() throws IOException {
// reset read pointers from previous frame's lock
mPngStream.clearDataChunks();
mPngStream.resetPos();
mChunk.unlockRead();
// locate next FCTL chunk
boolean ihdrCopied = false;
while (mChunk.typeCode != CODE_fcTL) {
switch (mChunk.typeCode) {
case CODE_IEND:
return null;
case CODE_IHDR:
mPngStream.setIHDR(mChunk.duplicateData());
break;
case CODE_acTL:
handleACTL(mChunk);
ihdrCopied = true;
break;
default:
handleOtherChunk(mChunk);
}
mChunk.parseNext();
}
// located at FCTL chunk
ApngFrame frame = new ApngFrame();
mChunk.assignTo(frame);
// locate next IDAT or fdAt chunk
mChunk.parseNext();// first move next from current FCTL
while (mChunk.typeCode != CODE_IDAT && mChunk.typeCode != CODE_fdAT) {
switch (mChunk.typeCode) {
case CODE_IEND:
return null;
case CODE_IHDR:
mPngStream.setIHDR(mChunk.duplicateData());
ihdrCopied = true;
break;
case CODE_acTL:
handleACTL(mChunk);
break;
default:
handleOtherChunk(mChunk);
}
mChunk.parseNext();
}
// located at first IDAT or fdAT chunk
// collect all consecutive dat chunks
boolean needUpdateIHDR = true;
int dataOffset = mChunk.getOffset();
while (mChunk.typeCode == CODE_fdAT || mChunk.typeCode == CODE_IDAT) {
if (needUpdateIHDR && (!ihdrCopied || mChunk.typeCode == CODE_fdAT)) {
mPngStream.updateIHDR(frame.getWidth(), frame.getHeight());
needUpdateIHDR = false;
}
if (mChunk.typeCode == CODE_fdAT) {
mPngStream.addDataChunk(new Fdat2IdatChunk(mChunk));
} else {
mPngStream.addDataChunk(new ApngMmapParserChunk(mChunk));
}
mChunk.parseNext();
}
// lock position for this frame's image as OutputStream
mChunk.lockRead(dataOffset);
frame.imageStream = mPngStream;
return frame;
}
2) Apng的消除操作
Apng的消除操作是在ApngFrameRender的render方法做的,方法如下:
/**
* 渲染當前幀畫面
*
* @param frame apng中當前幀
* @return 渲染合成後的當前幀影象
*/
public Bitmap render(ApngFrame frame, Bitmap frameBmp) {
// 執行消除操作
dispose(frame);
// 合成當前幀
blend(frame, frameBmp);
return mRenderFrame;
}
dispose(ApngFrame frame)方法如下:
/**
* 幀影象析構消除 - 提交結果
*/
private void dispose(ApngFrame frame) {
// last frame dispose op
switch (mLastDisposeOp) {
case APNG_DISPOSE_OP_NONE:
// no op
break;
case APNG_DISPOSE_OP_BACKGROUND:
// clear rect
mRenderCanvas.clipRect(mDisposeRect);
mRenderCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
mRenderCanvas.clipRect(mFullRect, Region.Op.REPLACE);
break;
case APNG_DISPOSE_OP_PREVIOUS:
// swap work and cache bitmap
Bitmap bmp = mRenderFrame;
mRenderFrame = mDisposedFrame;
mDisposedFrame = bmp;
mRenderCanvas.setBitmap(mRenderFrame);
mDisposeCanvas.setBitmap(mDisposedFrame);
break;
}
// current frame dispose op
mLastDisposeOp = frame.getDisposeOp();
switch (mLastDisposeOp) {
case APNG_DISPOSE_OP_NONE:
// no op
break;
case APNG_DISPOSE_OP_BACKGROUND:
// cache rect for next clear dispose
int x = frame.getxOff();
int y = frame.getyOff();
mDisposeRect.set(x, y, x + frame.getWidth(), y + frame.getHeight());
break;
case APNG_DISPOSE_OP_PREVIOUS:
// cache bmp for next restore dispose
mDisposeCanvas.clipRect(mFullRect, Region.Op.REPLACE);
mDisposeCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
mDisposeCanvas.drawBitmap(mRenderFrame, 0, 0, null);
break;
}
}
3) Apng的合成操作
Apng的合成操作是在每一幀經過dispose之後做的,具體方法是blend(ApngFrame frame, Bitmap frameBmp),程式碼如下:
/**
* 幀影象合成
*/
private void blend(ApngFrame frame, Bitmap frameBmp) {
int xOff = frame.getxOff();
int yOff = frame.getyOff();
mRenderCanvas.clipRect(xOff, yOff, xOff + frame.getWidth(), yOff + frame.getHeight());
if (frame.getBlendOp() == APNG_BLEND_OP_SOURCE) {
mRenderCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
}
mRenderCanvas.drawBitmap(frameBmp, xOff, yOff, null);
mRenderCanvas.clipRect(mFullRect, Region.Op.REPLACE);
}
4) Apng的繪製
Apng的每一幀經過消除、合成操作之後,就可以在View上面draw,具體程式碼如下:
/**
* draw the appointed frame
*/
private void drawFrame(AnimParams animItem, ApngFrame frame, Bitmap frameBmp) {
if (surfaceEnabled && !isInterrupted()) {
//start to draw the frame
try {
Matrix matrix = new Matrix();
matrix.setScale(mScale, mScale);
Bitmap bmp = mFrameRender.render(frame, frameBmp);
//saveBitmap(bmp, index);
index ++;
Canvas canvas = getHolder().lockCanvas();
//anti-aliasing
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
float[] tranLeftAndTop = ApngUtils.getTranLeftAndTop(canvas, bmp, animItem.align, mScale, animItem.percent);
canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
matrix.postTranslate(tranLeftAndTop[0], tranLeftAndTop[1]);
canvas.drawBitmap(bmp, matrix, null);
getHolder().unlockCanvasAndPost(canvas); // unlock the canvas
} catch (Exception e) {
Log.e(TAG, "draw error msg:" + Log.getStackTraceString(e));
}
}
}
4、實體
我們是在SurfaceView上面來繪製Apng的每一幀,例子如下:
Activity程式碼:
public class MainActivity extends Activity{
private ApngSurfaceView mApngSurfaceView;
private static final String COLOR_BALL_IMAGE_PATH = "assets://color_ball.png";
//private static final String CAR_IMAGE_PATH = "assets://car.png";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mApngSurfaceView = (ApngSurfaceView)findViewById(R.id.apng_surface_view);
Button startPlay = (Button) findViewById(R.id.start_play);
startPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playAnim();
}
});
}
private void playAnim(){
File file = FileUtils.processApngFile(COLOR_BALL_IMAGE_PATH, this);
if(file == null) return;
AnimParams animItem = new AnimParams();
animItem.align = 2;
animItem.imagePath = file.getAbsolutePath();
animItem.isHasBackground = true;
animItem.percent = 0.5f;
mApngSurfaceView.addApngForPlay(animItem);
}
}
Layout程式碼:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
tools:context=".MainActivity">
<com.apng.ApngSurfaceView
android:id="@+id/apng_surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />
<Button
android:id="@+id/start_play"
android:text="@string/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
RelativeLayout>
我們把一張Apng圖片放到Asset目錄下,透過ApngSurfaceView來播放。
說明
SakuApng的作者:ltf、xing.hu。
SakuApng地址:Apng的專案地址-SakuApng。
https://github.com/KeNanStar/SakuApng
例子演示:
汽車動畫.gif
●編號368,輸入編號直達本文
●輸入m獲取到文章目錄
Java程式設計
更多推薦《18個技術類公眾微信》
涵蓋:程式人生、演演算法與資料結構、駭客技術與網路安全、大資料技術、前端開發、Java、Python、Web開發、安卓開發、iOS開發、C/C++、.NET、Linux、資料庫、運維等。