200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > android设置图片 透明度渐变效果 android 自定义属性实现 ImageView 透明度渐变效果...

android设置图片 透明度渐变效果 android 自定义属性实现 ImageView 透明度渐变效果...

时间:2022-10-28 23:15:03

相关推荐

android设置图片 透明度渐变效果 android 自定义属性实现 ImageView 透明度渐变效果...

先看效果图:

第一步:

在valuses下面自定义目录:

第二步:

自定义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="/apk/res/com.jiaruihuademo.myattrimageview"

xmlns:tools="/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity" >

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"/>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。