2012年8月6日 星期一

Android:使用Canvas以及ShapeDrawable繪圖

XML File


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
<!--自建繼承View類別之元件,命名方法為套件名稱.類別名稱,
   圖形會繪製在此處 -->
    <com.example.CustomDrawableView1
        android:id="@+id/CustomDrawableView1"
        android:layout_width="match_parent"
        android:layout_height="420dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="變更色彩" />

</LinearLayout>

自建繼承View的Class


package com.example;

import ...
//建立一個類別,並繼承View,原先用來設定為程式畫面
//但是本例還是將成果希望可以利用XML排版
public class CustomDrawableView1 extends View {
//宣告一個Drawable子類別ShapeDrawable變數,用來繪製幾何圖形用
ShapeDrawable sd1;
    //自建繼承View類別之建構子,參數部分傳入兩個變數,Context以及AttributeSet
//使用AttributeSet參數後,我們在主程式中連接的XML檔中加入自建類別的元件
//就可以控制將欲產生的幾何圖形產生在該元件中
public CustomDrawableView1(Context context, AttributeSet attr) {
super(context, attr);
// TODO Auto-generated constructor stub
//宣告設定左上點座標以及長寬用的變數
int x1 = 10;
int y1 = 10;
int w1 = 150;
int h1 = 300;
//建立ShapeDrawable物件,產生的物件用來繪製出橢圓形
sd1 = new ShapeDrawable(new OvalShape());
//設定邊界
sd1.setBounds(x1, y1, x1 + w1, y1 + h1);

}

@Override
//繼承View後所產生的CallBack方法
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
int r = (int) (256 * Math.random());
int g = (int) (256 * Math.random());
int b = (int) (256 * Math.random());
//取得畫筆繪製顏色
sd1.getPaint().setARGB(0xff, r, g, b);
//在Canvas畫布上繪製出指定圖形
sd1.draw(canvas);

}

}

主程式

package com.example;

import ...

public class MainActivity extends Activity {
//宣告自建類別變數
CustomDrawableView1 customDrawableView;
Button but1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findView();
but1.setOnClickListener(new OnClickListener() {

public void onClick(View view) {
// TODO Auto-generated method stub
customDrawableView.invalidate();// 清掉畫面,會自動再呼叫callback方法onDraw()重新繪製
}

});
}

private void findView() {
// TODO Auto-generated method stub
               //在主程式中取得自建類別之物件,來源源自於XML中的一個元件
customDrawableView = (CustomDrawableView1) findViewById(R.id.CustomDrawableView1);
but1 = (Button) findViewById(R.id.button1);

}

}


沒有留言:

張貼留言