문제

I have 854X480 android screen size.

But, when I use drawRect(new Rect(0, 0, 570, 320), null) this will fit the entire screen.

MainActivity.java

public class MainActivity extends Activity
{
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(new MainLayout(this));
  }
}
class MainLayout extends RelativeLayout
{
  public MainLayout(Context context)
  {
    super(context);
    setWillNotDraw(false);
  }
  @Override
  public void onDraw(Canvas canvas)
  {
    super.onDraw(canvas);
    setBackgroundColor(Color.WHITE);
    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    canvas.drawRect(new Rect(0, 0, 570, 320), paint);
  }
}

Shouldn't it be canvas.drawRect(new Rect(0, 0, 854, 480), paint) that will fit entire screen? Why does the unit I use in Rect class ((570, 320) in this case) differ from my screen size?

도움이 되었습니까?

해결책

I think that's because you are hardcoding pixels, that fit for one screen. Better way would be to scale them according to device density. Here is the method for that.

public static int convertDpToPixel(float dp) {  
    return (int) (dp * (DEVICE_DENSITY_DPI / 160f));
}

Define DEVICE_DENSITY_DPI as a global object at Application level as:

DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager)getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);

DEVICE_DENSITY_DPI = metrics.densityDpi;    

Then, use it as follows:

class MainLayout extends RelativeLayout
{
  final int WIDTH = convertDpToPixel(570);
  final int HEIGHT = convertDpToPixel(320);      

  public MainLayout(Context context)
  {
    super(context);
    setWillNotDraw(false);
  }

  @Override
  public void onDraw(Canvas canvas)
  {
    super.onDraw(canvas);
    setBackgroundColor(Color.WHITE);
    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    canvas.drawRect(new Rect(0, 0, WIDTH, HEIGHT), paint);
  }
}

Now the values will automatically change according to the device width and height, also make sure to layout MainLayout with attributes match_parent.

Hope that helps. :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top