Narcís Calvet
Narcís Calvet

Reputation: 7452

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!

Upvotes: 6

Views: 12925

Answers (2)

Konstantin Burov
Konstantin Burov

Reputation: 69228

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);

Upvotes: 9

Lumis
Lumis

Reputation: 21639

Use Paint pen = new Paint(Paint.ANTI_ALIAS_FLAG);

Upvotes: 2

Related Questions