Android subpixel rendering

2019-03-03 17:25发布

问题:

I have a line that should get thinner the longer it gets. The problem is, that you can clearly see a jump when it gets a pixel thinner. Is there a way to do subpixel rendering/antialiasing on Android?

canvas.drawRect() takes float values, but it's ignoring those. Here's the code:

@Override
protected void onDraw(Canvas canvas) {
    float width = getMeasuredWidth() / (float) getMeasuredHeight()  * getMinimumHeight();
    float left = (getMeasuredWidth() - width) / 2.0f;
    canvas.drawRect(left, 0, left + width, getMeasuredHeight(), paint);
    super.onDraw(canvas);
}

The paint object has ANTI_ALIAS_FLAG enabled and contains a solid color.

This is the default line:

This is when it gets longer and thinner. It should have some anti aliasing on the sides, though to make the whole transition seems smoother.

回答1:

This seems to do a better job:

@Override
protected void onDraw(Canvas canvas) {
    float width = getMeasuredWidth() / (float) getMeasuredHeight()  * getMinimumHeight();
    float left = (getMeasuredWidth() - width) / 2.0f;
    paint.setStrokeWidth(width * getResources().getDisplayMetrics().density);
    canvas.drawLine(left, 0, left, getMeasuredHeight(), paint);
    super.onDraw(canvas);
}