问题
I need to draw an exact square 3x3 cm on the screen, you need the exact dimensions in any type of screen as design work.
The result in a Samsung Ace is 2.8 cm, the result is not exact.
Java...
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
float ld = 30 * metrics.densityDpi * (metrics.density/25.4f);
bitmap = Bitmap.createBitmap((int) ld, (int) ld, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.WHITE);
imageView.setImageBitmap(bitmap);
canvas.drawRect(0, 0, (float) ld, (float) ld, paint);
XML...
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image_view"
android:scaleType="center"/>
thank you very much
回答1:
I think you need to use the dpi in the specific directions x and y eg:
// We want 30/25.4 inches but in dots
float inches = 30/25.4f;
float xdpi = getResources().getDisplayMetrics().xdpi;
float xDots = inches * xdpi;
float ydpi = getResources().getDisplayMetrics().ydpi;
float yDots = inches * ydpi;
Paint paint = new Paint();
paint.setColor(Color.WHITE);
canvas.drawRect(0, 0, xDots, yDots, paint);
Then you will have more chance, but they are not accurate for every phone. I got the following results after placing this code in the onDraw() method of and Android app:
Nexus 7: 2.8 cm
Galaxy Nexus 3.0 cm
HTC Sensation 3.0 cm
HTC Desire HD 2.7 cm
So it is not exact in all cases.
来源:https://stackoverflow.com/questions/15035792/draw-square-3x3-cm-in-android