Android设置Alpha值实现图片渐变效果
16lz
2021-01-26
我们要将一个张图片显示在屏幕上,首先需要创建一个显示图片的对象,在Android 中,这个对象是ImageView对象,然后通过setImageResources 方法来设置要显示的图片资源索引。当然,还可以对图片执行一些其它的操作,比如设置它的Alpha值等。这里通过一个示例来给大家演示,我们另起一个线程来改变图片的Alpha值。
Activity01类
Java代码
Activity01类
Java代码
- package xiaohang.zhimeng;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.widget.ImageView;
- import android.widget.TextView;
-
- public class Activity01 extends Activity {
- // 声明ImageView对象
- ImageView imageView;
- // 声明TextView
- TextView textView;
- // ImageView的alpha值
- int image_alpha = 255;
- // Handler对象用来给UI_Thread的MessageQueue发送消息
- Handler mHandler;
- // 线程是否运行判断变量
- boolean isrung = false;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- isrung = true;
- // 获得ImageView的对象
- imageView = (ImageView) this.findViewById(R.id.ImageView01);
- textView = (TextView) this.findViewById(R.id.TextView01);
- // 设置imageView的图片资源。同样可以再xml布局中像下面这样写
- // android:src="@drawable/logo"
- imageView.setImageResource(R.drawable.logo);
- // 设置imageView的Alpha值
- imageView.setAlpha(image_alpha);
- // 开启一个线程来让Alpha值递减
- new Thread(new Runnable() {
- @Override
- public void run() {
- while (isrung) {
- try {
- Thread.sleep(200);
- // 更新Alpha值
- updateAlpha();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }).start();
- // 接受消息之后更新imageview视图
- mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- imageView.setAlpha(image_alpha);
- // 设置textview显示当前的Alpha值
- textView.setText("现在的alpha值是:" + Integer.toString(image_alpha));
- // 刷新视图
- imageView.invalidate();
- }
- };
- }
-
- // 更新Alpha
- public void updateAlpha() {
- if (image_alpha - 7 >= 0) {
- image_alpha -= 7;
- } else {
- image_alpha = 0;
- isrung = false;
- }
- // 发送需要更新imageview视图的消息-->这里是发给主线程
- mHandler.sendMessage(mHandler.obtainMessage());
- }
- }
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <ImageView
- android:id="@+id/ImageView01"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- />
- <TextView
- android:id="@+id/TextView01"
- android:layout_below="@id/ImageView01"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- />
- </LinearLayout>
更多相关文章
- Android(安卓)的消息机制(1)
- android之Fresco框架--Fresco基本使用
- android 对话框弹出位置和透明度的设置
- android中的Context(android内核学习记录)
- Android(安卓)Activity管理之Activity栈
- 我的开源项目:Android图片剪裁库
- 干货 | Kotlin超棒的语言特性
- Android(安卓)Log 及eclipse中文乱码
- 【Android开发学习41】Android(安卓)将文字转为为图片drawText