2011-03-11 73 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)

希望帮助