2011-03-02 181 views
0

我发现了一些线条画的代码,但它不起作用。任何一个可以帮助我在android中绘制一条线?如何在android中绘制一条线?

这里是我的XML:

<?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" 
    android:id="@+id/layoutmain"> 
<TextView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello" 
/> 
</LinearLayout> 

这里是我的代码类:

public class DrawPoints extends Activity implements OnTouchListener { 
    static int i = 0; 
    static float static_x = 0; 
    static float static_y = 0; 
    static float static_x1 = 0; 
    static float static_y1 = 0; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     View topLayout = this.findViewById(R.id.layoutmain); 
     // register for events for the view, previously 
     topLayout.setOnTouchListener((OnTouchListener) this); 
    } 

    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     String tag = null; 

     if (i == 0) { 
      static_x = event.getX(); 
      static_y = event.getY(); 
      i = 1; 
     } else { 
      static_x1 = event.getX(); 
      static_y1 = event.getY(); 

     } 

     if (i == 1) { 
      Paint p = new Paint(); 
      p.setColor(Color.WHITE); 
      p.setStyle(Paint.Style.STROKE); 
      Canvas canvas = new Canvas(); 
      canvas.drawColor(Color.BLUE); 

      canvas.drawLine(static_x, static_y, static_x1, static_y1, p); 
      i = 0; 
     } 
     return false; 
    } 

} 
+0

还可以参考本示例,其是2D图形的演示:[Android的2D图形演示](http://marakana.com/tutorials/android/2d-graphics-example.html) – Maverick 2011-11-22 04:52:02

回答

14

你可以简单地在你的XML布局这样写:

<View 
    android:layout_width="fill_parent" 
    android:layout_height="1dp" 
    android:background="#cccccc" 
    android:paddingTop="20dp" /> 

这将创建一个水平线。

+0

好的,你把这个视图,但我不需要这个,因为你可以看到我想画线的任何点,当你用户触摸屏幕的两点时,一条直线将画在帆布或任何视图。 – Herry 2011-05-13 05:16:48

+0

谢谢...我真的很想这 – 2013-11-15 13:39:11

+0

这是一些邪恶的侧面思考 – user1301428 2016-03-14 08:22:42

2

这是我的小把戏解决方案与penchoco解决方案相比可提高绘图性能快于163倍

<View 
    android:id="@+id/line" 
    android:layout_width="fill_parent" 
    android:layout_height="1px" 
    android:background="@drawable/ic_line" 
</View> 

penchoco解决方案的唯一区别的是使用9 patchClick here to download 9 patch image绘制的1x1像素而不是颜色。

android:background="@drawable/ic_line" 

问: 任何人都可以解释为什么使用9修补图像性能提升超过163倍,落后情况下,使一个神奇的结果是实现?

由于

+1

对于你的问题的更多答案,你可以问这个新的问题。通过这种方式,其他人也可以看到这个问题。 – Herry 2012-05-07 04:58:32