2011-03-11 72 views
3

我想製作一個溫度計。爲此,我使用ImageView將 插入到佈局中的溫度計(png文件)的圖像。現在我想在這張圖上畫一條線來顯示溫度讀數的效果。如何在佈局上繪製動態繪圖

這是我的代碼。

main.xml中

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
<ImageView 
</ImageView> 
<com.focusone.Android.DrawExample.CustomDrawableView  
    android:id="@+id/custom_drawable_view" 
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content" 
    height='100' 
    /> 
</AbsoluteLayout> 

DrawExample.java

package com.focusone.Android.DrawExample; 

public class DrawExample extends Activity { 
    /** Called when the activity is first created. */ 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

    } 

} 

CustomDrawableView.java

public class CustomDrawableView extends View { 
    private ShapeDrawable mDrawable; 

    public CustomDrawableView(Context v,AttributeSet as){ 
     super(v,as); 
     drawShape(as); 
    } 
    public void drawShape(AttributeSet ast) { 

     int x =45; int y=15 ; int width=5; int height=0 ; 
        height= Integer.parseInt(ast.getAttributeValue(null, "height")); 
        mDrawable = new ShapeDrawable(new RectShape()); 
        mDrawable.getPaint().setColor(0xff74AC23); 
        mDrawable.setBounds(x, y, x + width, y + height); 
    } 
    protected void onDraw(Canvas canvas) { 
     mDrawable.draw(canvas); 
    } 
} 

現在我可以在溫度計圖像上畫一條線運用這個程序。

但是,如何在運行時更改線的高度。 因爲height = 100是寫在xml文件中,所以我不知道如何改變它。

請有人幫助我。

+0

順便說..你爲什麼不擴展ImageView類?那麼你將不必關心繪製圖像。你可以專注於繪製你的形狀。 – Chris 2011-03-11 19:56:42

+0

我會嘗試一個FrameLayout。第一個圖像然後是自定義視圖,因爲AbsoluteLayout已被棄用。要將溫度計放置在屏幕上的任何位置,可以通過設置其左上和右邊距將此FrameLayout插入到RelativeLayout中。 – Lumis 2011-03-12 05:41:40

回答

1

首先我覺得你並不需要在drawShape(AttributeSet中AST)將屬性只是高度在你的構造CustomDrawableView喜歡()。然後,當克里斯說你應該在自定義視圖中的另一種方法像

public void setTemperature(int tmp){ 
    drawShape(tmp); 
    invalidate(); //this will call onDraw() 
} 

在您的主要活動對您的自定義視圖的引用,以便您可以調用它的公共方法

CustomDrawableView temperatureView = 
        (CustomDrawableView) findViewById(R.id.custom_drawable_view); 

    temperatureView.setTemperature(50); 
+0

爲什麼即使'setTemperature'靜態?在我看來,這是沒有道理的。當然,有人可能會認爲你只是在繪製一種溫度。但是,如果你想再繪製一個溫度,也敢。實例變量也會變得不必要,以及... – Atmocreations 2012-03-05 20:49:51

+0

你說得對,這裏沒有必要與靜態方法進行合作。 – Lumis 2012-03-06 10:24:17

1

您可以:

  • 使「高度」你CustomDrawableView
  • 成員然後創造一個你改變高度值的方法setHeight(int height)
  • 然後在您的活動中使用(CustomDrawableView)findViewById(R.id.custom_drawable_view)來獲取對您的viewObject的引用。
  • 然後將值更改爲你調用setHeight(x)

希望幫助