您的位置:首页 > 移动开发 > Android开发

android 自定义属性实现 ImageView 透明度渐变效果

2013-11-13 10:41 741 查看
先看效果图:







第一步:

在valuses下面自定义目录:

<?xml version="1.0" encoding="utf-8"?>

<resources>

    <!-- 定义一个属性 -->

    <attr name="duration"></attr>

    <!-- 定义一个styleable对象来组合多个属性 -->

    <declare-styleable name="AlphaImageView">

        <attr name="duration"/>

    </declare-styleable>

</resources>

第二步:

自定义ImageView

package com.jiaruihuademo.myattrimageview;

import java.util.Timer;

import java.util.TimerTask;

import com.jiaruihuademo.myattrimageview.R;

import android.content.Context;

import android.content.res.TypedArray;

import android.graphics.Canvas;

import android.os.Handler;

import android.os.Message;

import android.util.AttributeSet;

import android.widget.ImageView;

public class AlphaImageView extends ImageView {
//图像透明度每次改变的大小
private int perAlpha = 0;
//当前图像的透明度
private int curAlpha = 0;
//每隔多长时间改变一次透明度
private int SPEED = 300;

public AlphaImageView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
//找到自定义的属性
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.AlphaImageView);
//获取duration参数
int duration = typedArray.getInt(R.styleable.AlphaImageView_duration, 0);
//计算透明度改变的大小
perAlpha = 255*SPEED/duration;
}

Handler handler = new Handler(){
public void handleMessage(Message msg) {
if (msg.what==0x123) {
curAlpha +=perAlpha;
if (curAlpha>255) {
curAlpha=255;

}
AlphaImageView.this.setAlpha(curAlpha);
}
};
};
@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() {
// TODO Auto-generated method stub
Message msg = new Message();
msg.what=0x123;
if (curAlpha>255) {
timer.cancel();
}else {
handler.sendMessage(msg);
}
}
}, 0,SPEED);

}

}

第三步:

在layout布局下:

<!-- 特别需要注意的是 xmlns:jiaruihuademo="http://schemas.android.com/apk/res/com.jiaruihuademo.myattrimageview"定义,看清楚 -->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:jiaruihuademo="http://schemas.android.com/apk/res/com.jiaruihuademo.myattrimageview"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity" >

    <com.jiaruihuademo.myattrimageview.AlphaImageView

        android:id="@+id/imageView1"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:layout_below="@+id/textView1"

        android:layout_centerHorizontal="true"

        android:src="@drawable/t01397599f43ebc8f8c"

        jiaruihuademo:duration="60000"/>

</RelativeLayout>

源码下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息