Below you can see the results after working with your code. It is almost like xml, but if you look at it with a mignifier, you may find some differences.
So, when drawing, there are some important things.
- Do not use int. You are losing accuracy. I replaced all int with float in your code.
- Be careful in the loop. You also lose accuracy in cycles.
General pattern in code:
float boxWidth = (getWidth() - mSideRectWidth) / 8; // I replaced int to float for (int i = 0; i < 8; i++) { float position = i * boxWidth; // loss of precision ... }
Better to calculate the position in the loop:
for (int i = 0; i < 8; i++) { float position = i * (getWidth() - mSideRectWidth) / 8; ... }
- Do not forget the stroke width. You will skip this value when calculating the positions of shapes and lines.
And here is my complete code:
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.text.TextPaint; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; public class Car extends View { private final Paint mBlackPaint = new Paint(); private final Paint mRedPaint = new Paint(); private final TextPaint mTextPaint; public static final int BOXES_COUNT = 8; private float oneDp; private float textSize; private float windowHeight; public Car(Context context, AttributeSet attrs) { super(context, attrs); oneDp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics()); windowHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics()); textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 15, getResources().getDisplayMetrics()); mRedPaint.setColor(Color.parseColor("#CC3333")); mBlackPaint.setAntiAlias(true); mBlackPaint.setColor(Color.BLACK); mBlackPaint.setStrokeWidth(oneDp); mBlackPaint.setStyle(Paint.Style.STROKE); mTextPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG); mTextPaint.setColor(Color.BLACK); mTextPaint.setTextAlign(Paint.Align.CENTER); mTextPaint.setTextSize(textSize); mWindowPaint = new Paint(); mWindowPaint.setAntiAlias(true); mWindowPaint.setColor(Color.parseColor("#CC3333")); mWindowPaint.setStyle(Paint.Style.STROKE); mWindowPaint.setStrokeWidth(oneDp); } private Paint mWindowPaint; RectF rect = new RectF(); RectF rect2 = new RectF(); @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (getWidth() == 0) return; int w = canvas.getWidth(); int h = canvas.getHeight();
Portrait 
Landscape 
Ilya Tretyakov
source share