Android : Draw a line continuously using Canvas in Android

on Sunday, September 7, 2014


I am using canvas to draw a line continuously. I will draw the line in relative layout. For static line, I done. But I don't know how to draw a line continuously as below figure. Could you suggest to me a algorithm to do it. Thank you so much. This is my code



//XML file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<RelativeLayout
android:id="@+id/canvas"
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_weight="1"
android:background="#d3d3d3" >
</RelativeLayout>

</RelativeLayout>


This is my code for static line



import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(new HeartGraphView (this));
setContentView(R.layout.activity_main);
RelativeLayout relativeLayout=(RelativeLayout)findViewById(R.id.canvas);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.FILL_PARENT);
HeartGraphView v = new HeartGraphView(this);
v.setLayoutParams(lp);
relativeLayout.addView(v);
}
public class HeartGraphView extends View {
public HeartGraphView (Context context) {
super(context);
// TODO Auto-generated constructor stub
}
int[] dataX={10,30,60,90,120,150,180,210,240,270};
int[] dataY={5,20,90,140,0,0,-50,-140,-20,100};
@Override
public void onDraw (Canvas canvas) {
int w;
int h;
h=280;
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(6);
for (int i = 0; i < dataX.length - 1; i++) {
canvas.drawLine(dataX[i], h/2-dataY[i], dataX[i+1], h/2-dataY[i+1],paint);

}

}
}

}


enter image description here


0 comments:

Post a Comment