Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drawLine problem with Paint.StrokeWidth = 1 in Android

I think I hit a nasty bug. The problem is that nearly horizontal lines with a slight gradient and using a Paint with StrokeWidth = 1 are not plotted, for example:

public class MyControl extends View {

   public MyControl(Context context) {
           super(context);
           // TODO Auto-generated constructor stub
   }

   @Override
   protected void onDraw(Canvas canvas)
   {
           super.onDraw(canvas);

       Paint pen = new Paint();
       pen.setColor(Color.RED);
       pen.setStrokeWidth(1);
       pen.setStyle(Paint.Style.STROKE);

           canvas.drawLine(100, 100, 200, 90, pen); //not painted
           canvas.drawLine(100, 100, 200, 100, pen);
           canvas.drawLine(100, 100, 200, 110, pen); //not painted
           canvas.drawLine(100, 100, 200, 120, pen); //not painted
           canvas.drawLine(100, 100, 200, 130, pen);

           pen.Color = Color.MAGENTA;
           pen.setStrokeWidth(2);

           canvas.drawLine(100, 200, 200, 190, pen);
           canvas.drawLine(100, 200, 200, 200, pen);
           canvas.drawLine(100, 200, 200, 210, pen);
           canvas.drawLine(100, 200, 200, 220, pen);
           canvas.drawLine(100, 200, 200, 230, pen);
   }

}

And using MyControl class this way:

public class prova extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);

           MyControl ctrl = new MyControl(this);
           setContentView(ctrl);
   }

}

Setting StrokeWidth to 0 or > 1 all lines are plotted.

Can anyone bring some light on this or should I submit this issue as an Android Issue?

Thanks in advance!

like image 987
Narcís Calvet Avatar asked Mar 21 '11 11:03

Narcís Calvet


1 Answers

By setting strokeWidth to 0 you say android to draw with a hairline width (which is usually one 1px on any device). If you set stroke width to 1 the value is then scaled, i.e. on ldpi devices it would be 0.75 * 1 = 0.75px. So the line might be not rendered at all. Setting ANTI_ALIAS_FLAG to your paint device might help:

Paint pen = new Paint(Paint.ANTI_ALIAS_FLAG);

Alternatively you can calculate the stroke width for current density:

pen.setStrokeWidth(1 / getResources().getDisplayMetrics().density);
like image 186
Konstantin Burov Avatar answered Sep 17 '22 23:09

Konstantin Burov