drawLine problem with Paint.StrokeWidth = 1 in Android

12,655

Solution 1

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

Solution 2

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

Share:
12,655
Narcís Calvet
Author by

Narcís Calvet

I'm a software developer and parent. In my free time I like to: ride on MTB, watch F.C. Barcelona (soccer) games and listen to prog music.

Updated on June 07, 2022

Comments

  • Narcís Calvet
    Narcís Calvet almost 2 years

    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!