如何自定义ImageView---并让其渐变出现(李刚老师)

public class AlphaImageView extends ImageView
{
    // 图像透明度每次改变的大小
    private int alphaDelta = 0;
    // 记录图片当前的透明度。
    private int curAlpha = 0;
    // 每隔多少毫秒透明度改变一次
    private final int SPEED = 300;
    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            if (msg.what == 0x123)
            {
                // 每次增加curAlpha的值
                curAlpha += alphaDelta;
                if (curAlpha > 255) curAlpha = 255;
                // 修改该ImageView的透明度
                AlphaImageView.this.setAlpha(curAlpha);
            }
        }
    };
    public AlphaImageView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.AlphaImageView);
        // 获取duration参数
        int duration = typedArray
                .getInt(R.styleable.AlphaImageView_duration, 0);
        // 计算图像透明度每次改变的大小
        alphaDelta = 255 * SPEED / duration;
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        this.setAlpha(curAlpha);
        super.onDraw(canvas);
        final Timer timer = new Timer();
        // 按固定间隔发送消息,通知系统改变图片的透明度
        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                Message msg = new Message();
                msg.what = 0x123;
                if (curAlpha >= 255)
                {
                    timer.cancel();
                }
                else
                {
                    handler.sendMessage(msg);
                }
            }
        }, 0, SPEED);
    }
}

 

posted @ 2013-05-27 16:19  linsen@java  阅读(351)  评论(0编辑  收藏  举报