Drawing a line with a certain pixel width

Rich picture Rich · Apr 16, 2011 · Viewed 10.7k times · Source

I would like to display X/Y data on a canvas using lines with a certain width (in pixels, or "dp" ideally). I have tried the setStrokeWidth(..) method of Paint, and that indeed does change the line width but it isn't what I need. In my case I've scaled my canvas to "real Engineering units" using matrix.preScale(xScale, yScale) so the X scale represents 0 to 100 and the Y is 0 to 1. The setStrokeWidth() method of the Paint object seems to set the stroke so that it follows my matrix preScale() settings. In other words, horizontal lines are drawn really thin, and vertical lines are drawn really thick.

Is there a way to configure the Paint so that no matter which direction the line is drawn, its width is a consistent number of pixels?

I have tried defining a Drawable that is a line, and making a ShapeDrawable from that, and then applying it to the Paint but ran into some nasty class casting errors at run time. This made me think that this was the wrong way to go about it. But maybe I gave up too soon.

I understand that are a number of Android plotting/charting packages available, some with source, but I'm really looking to understand the platform here, rather than using a third-party solution.

Thanks for any hints! Rich

Answer

Android3 picture Android3 · Jun 14, 2011

For example on Android : paint.setStrokeWidth(3); This method sets line width. In this case, line width is 3 pixels. I am searching just like this method on BlackBerry.

Try this :

    Graphics.setColor(Color.RED);
    Graphics.setStrokeWidth(20);
    Graphics.drawRect(0, 0, 100, 100);

They are available in net.rim.device.api.ui.Graphics package.