Android通過Alpha實現漸層效果的幾個方法

來源:互聯網
上載者:User

標籤:android


原理 : 通過改變控制透明度的Alpha值來實現漸層效果


方法一 : 使用XML

    步驟一 : 首先,我們要在res檔案夾下的anim檔案夾裡建立一個.xml檔案(這裡我建立的是alpha.xml)

    設定開始時透明度為0.0(透明):android:fromAlpha="0.0"

    設定結束時透明度1.0(不透明):android:toAlpha="1.0"


                        

    <alpha

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

    android:fromAlpha="0.0"

    android:toAlpha="1.0"

    android:duration="2000">

    </alpha>


    步驟二 : 接下來就要使用Animation類來實現效果了


    @Override

    protected void onCreate(Bundle savedInstanceState)

    {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);


ImageView but=(ImageView)findViewById(R.id.mainButton);


Animation mAnimation = AnimationUtils.loadAnimation(this, R.anim.alpha); 

but.startAnimation(mAnimation);

    }


方法二 : 使用Paint類

    方法 : 通過Paint.setAlpha();改變圖的Alpha值


     

public class MainActivity extends Activity implements OnTouchListener{

     Paint paint=new Paint();

     

     //設定初始Alpha為100(不透明)

     int al=100;


   

@Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

setContentView(new RenderView(this));

    }


    class RenderView extends View {

       

        protected void onDraw(Canvas canvas){

                        //擷取螢幕長、寬

int height=canvas.getHeight();

int width=canvas.getWidth();

                        //畫一個完全填充的紅色長方形,並改變Alpha值

paint.setStyle(Paint.Style.STROKE);

paint.setColor(Color.RED);

paint.setAlpha(al--);            //改變Alpha(透明度)值

canvas.drawRect(width/2,2,width/3*2,height/2,paint);

                         invalidate();

}

}

}

本文出自 “12608835” 部落格,請務必保留此出處http://12618835.blog.51cto.com/12608835/1920183

Android通過Alpha實現漸層效果的幾個方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.