首先看下效果图,有点卡顿,这是因为我是用android studio的screen record来录制手机视频的,然后找不到合适的mp4->gif的软件,就使用了一个录屏的软件,所以有点卡顿,但是实际上跑起来还是很柔滑的。
这是使用了自定义View的方法,下面上代码:
/**
* Created by hzlinxuanxuan on 2015/9/5.
*/
public class DrawBitmapView extends View {
private Bitmap bitmap;
//每次刷新比上一次多显示图片的比例
private float step = 0.01f;
//已经显示图片的比例
private float currentScale = 0.0f;
//显示图片的区域
private RectF dst;
private Rect src;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1)
invalidate();
}
};
public DrawBitmapView(Context context, AttributeSet attrs) {
super(context, attrs);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 2;
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.snail, opts);
dst = new RectF();
dst.left = 0;
dst.top = 0;
dst.bottom = bitmap.getHeight();
src = new Rect();
src.left = 0;
src.top = 0;
src.bottom = bitmap.getHeight();
}
/**
* 默认从左到右显示
*/
@Override
protected void onDraw(Canvas canvas) {
currentScale = currentScale + step > 1 ? 1 : currentScale + step;
dst.right = bitmap.getWidth() * currentScale;
src.right = (int) (bitmap.getWidth() * currentScale);
/*
* drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint);
* Rect src: 是对图片进行裁截,若是空null则显示整个图片
* RectF dst:是图片在Canvas画布中显示的区域,
* 大于src则把src的裁截区放大,
* 小于src则把src的裁截区缩小。
* 当想要让图片以画卷方式展现的话,主要是设置src大小,这边是默认从左到右显示,所以每次只要修改src中right的大小就好
*/
canvas.drawBitmap(bitmap, src, dst, null);
if (currentScale >= 1) {
//当显示完图片,重置,循环显示
currentScale = 0 - step;
}
//不想让整个页面处于频繁刷新的状态,这里延迟了10ms来刷新该页面
handler.sendEmptyMessageDelayed(1, 10);
}
}
<com.think.linxuanxuan.sampleapplication.other.DrawBitmapView
android:layout_width="match_parent"
android:layout_height="220dp"/>
这里是直接继承自View,当然读者可以直接让他继承imageView,这样就可以直接在xml文件中为其指定src,然后在ondraw函数中使用
Drawable drawable=getDrawable();
然后对该drawable进行操作即可,例子中使用的是默认图片,这里读者可以自己diy啦
解读代码:
该代码中主要是每次都画图片的一部分,然后连起来,像播放电影画面一样,给人是完整柔滑的展开图片的感觉。那每次画图片多少呢,是用Rect src该变量决定的,具体代码中有说明。
具体代码git地址:
git clone https://github.com/LxxCaroline/SampleApplication.git
该地址里面还有很多其他的sample,读者如果有兴趣可以都打开看看,该例子的代码是在DrawBitmapView.java和activity_draw.xml中