10

仿新浪微博图片预加载效果

 3 years ago
source link: https://www.longdw.com/2012/10/31/sina-loadingimage-android/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

仿新浪微博图片预加载效果 – longdw跳至内容

longdw

longdw

stay hungry stay foolish

最近公司的项目中要求加入新浪微博中查看微博详情的功能,看了看新浪微博客户端有个效果挺不错的,就是在图片显示之前会有一张默认的图片,会随着加载进度的增加默认图片有种慢慢装满水的效果,如下:

以前也看到过这种效果,一直没有时间弄,这次正好项目中要用到就研究了一下实现。

开始认为的作法是要改变图片Alpha值,方法行不通。研究了一番,可以自定义ImageView,在onDraw方法中可以使用canvas.drawRect(rect, paint),问题是怎么获取默认图片的绘制区域也就是Rect,Rect rect = canvas.getClipBounds()方法可以获取到图片的裁剪区域,另外rect.top和rect.bottom可以获取到矩形区域的顶部和底部位置,程序中我测试了一下,rect.top为0,rect.bottom为图片的高度,可以通过改变rect.top的值来控制所绘矩形的高度,下面附上我写demo:

package com.loading;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.ImageView;

public class LoadingImageView extends ImageView {

	public LoadingImageView(Context context) {
		super(context);

	}

	public LoadingImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public LoadingImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	int i = 210;

	@Override
	protected void onDraw(Canvas canvas) {
		Paint paint = new Paint();
		paint.setColor(Color.GREEN);

		Rect rect = canvas.getClipBounds();
		rect.top += i;
		System.out.println(rect.bottom + "---" + rect.top);
		canvas.drawRect(rect, paint);

		i -= 10;
		if (i >= 0) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
						e.printStackTrace();
					}
					mHandler.sendEmptyMessage(1);
				}
			}).start();
		}

		super.onDraw(canvas);
	}

	Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			invalidate();
		}
	};

}

根据下载的进度来确定所画矩形的高度可以动态的控制rect.top的值。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK