Reputation: 23
I've been trying to draw a polyline on a canvas. There are no errors in my codes, but the connected sequence of line segments are not showing.Please find code snippet below;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;
public class MyView extends View {
private Paint redPaint;
public MyView(Context context) {
super(context, null);
redPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
redPaint.setStyle(Paint.Style.STROKE);
redPaint.setColor(0xffff0000);
redPaint.setStrokeWidth(5);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(10,30,200,200,redPaint);
canvas.drawCircle(300,300,250,redPaint);
Path mylines=new Path();
mylines.moveTo(0,0);
mylines.lineTo(1,1);
mylines.lineTo(2,2);
mylines.lineTo(3,3);
mylines.lineTo(4,4);
Paint GreenPaint=new Paint();
GreenPaint.setARGB(255,0,255,0);
canvas.drawPath(mylines,GreenPaint);
}
}
Upvotes: 2
Views: 1235
Reputation: 62831
Your code is largely correct. You do not completely initialized GreenPaint
like you do redPaint
and that is a problem. The second issue, although it may not be a problem, is that your polyline shape is so small that you may miss it even with a fully initialized GreenPaint
.
Here is an updated version of your custom view with an additional constructor and an initialized greenPaint
. I also changed the shape of the polyline and made it larger to be easily seen - it is just a speck in your code. In addition I moved object allocation out of onDraw()
.
public class MyView extends View {
Path mylines = new Path();
private Paint redPaint;
private Paint greenPaint;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context) {
super(context, null);
init();
}
private void init() {
redPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
redPaint.setStyle(Paint.Style.STROKE);
redPaint.setColor(0xffff0000);
redPaint.setStrokeWidth(5);
greenPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
greenPaint.setStyle(Paint.Style.STROKE);
greenPaint.setARGB(255, 0, 255, 0);
greenPaint.setStrokeWidth(5);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(10, 30, 200, 200, redPaint);
canvas.drawCircle(300, 300, 250, redPaint);
mylines.moveTo(0, 0);
mylines.lineTo(200, 50);
mylines.lineTo(300, 150);
mylines.lineTo(400, 250);
mylines.lineTo(500, 300);
canvas.drawPath(mylines, greenPaint);
}
}
Here is the display. (I added a gray background for visibility of the view but it is not needed.)
Upvotes: 2