java Android 中 Paint.StrokeWidth = 1 的 drawLine 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5377052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
drawLine problem with Paint.StrokeWidth = 1 in Android
提问by Narcís Calvet
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:
我想我遇到了一个讨厌的错误。问题是没有绘制带有轻微渐变的几乎水平线,并使用 StrokeWidth = 1 的 Paint,例如:
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:
并以这种方式使用 MyControl 类:
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.
将 StrokeWidth 设置为 0 或 > 1 将绘制所有线条。
Can anyone bring some light on this or should I submit this issue as an Android Issue?
任何人都可以对此有所了解,还是应该将此问题作为Android 问题提交?
Thanks in advance!
提前致谢!
回答by Konstantin Burov
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:
通过将 strokeWidth 设置为 0,你说 android 使用细线宽度(在任何设备上通常为 1px)进行绘制。如果您将笔触宽度设置为 1,则该值将被缩放,即在 ldpi 设备上,它将是 0.75 * 1 = 0.75px。所以这条线可能根本没有被渲染。将 ANTI_ALIAS_FLAG 设置为您的绘画设备可能会有所帮助:
Paint pen = new Paint(Paint.ANTI_ALIAS_FLAG);
Alternatively you can calculate the stroke width for current density:
或者,您可以计算电流密度的笔划宽度:
pen.setStrokeWidth(1 / getResources().getDisplayMetrics().density);
回答by Lumis
Use
Paint pen = new Paint(Paint.ANTI_ALIAS_FLAG);
利用
Paint pen = new Paint(Paint.ANTI_ALIAS_FLAG);