draw a figure of the same length on Android

Asked 2 years ago, Updated 2 years ago, 46 views

The following program shows squares, but I would like to draw a square of the same size on any device. What should I do?

I don't care about the 0.1mm unit, but I'd like to make it about the same size.
Now, the size is determined by the pdx of each terminal.Please let me know if there is a good way.

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;


public class MainActivity extensions ActionBarActivity {
    @ Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView (new CanvasV(this));
    }
}


public class CanvasVextends View {
    private intrectW = 200;
    private intrectH = 200;
    private Rect;
    private Paint;

    public CanvasV (Context context) {
        super(context);
        rect = new Rect();
        paint = new Paint();
        paint.setColor (0xFF008800);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin (Paint.Join.ROUND);
        paint.setStrokeCap (Paint.Cap.ROUND);
        paint.setStrokeWidth(10);
    }

    @ Override
    protected void onDraw (Canvas canvas) {
        canvas.drawRect(rect, paint);
        rect.set(10,10,rectW,rectH);
        invalidate();
    }
}

I use Android Studio for my environment.

android

2022-09-30 19:56

1 Answers

Use the dp unit.
http://developer.android.com/intl/ja/guide/practices/screens_support.html#density-independence

Different terminals have different pixel densities (how many pixels are packed per inch).This is why the size varies depending on the model.

On Android, the unit Density-independent pixel(dp) is provided.The formula is dp = number of pixels x (160/pixel density).This is a unit based on 160 dpi (160 dots per inch), independent of pixel density and of the same size for any terminal.

Layout XML allows you to add units, but since Java code is specified in pixels, the dp unit should be in pixels with the following code:(in the previous official document)

//The gesture threshold expressed indp
private static final float GESTURE_THRESHOLD_DP = 16.0f;

// Get the screen's density scale
final float scale=getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
mGestureThreshold=(int) (GESTURE_THRESHOLD_DP*scale+0.5f);


2022-09-30 19:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.