简体   繁体   中英

Loading images to different screen sizes and densities in game development?

The code below draws a square and circle on different screen sizes distance between images changes. It would be more messed up with actual bitmaps and different screen sizes and densities. Here is the code

package com.badlogic.androidgames;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class ShapeTest extends Activity {
class RenderView extends View {        
    Paint paint;

    public RenderView(Context context) {
        super(context);
        paint = new Paint();            
    }

    protected void onDraw(Canvas canvas) {
        canvas.drawRGB(255, 255, 255);            
        paint.setColor(Color.RED);
        canvas.drawLine(0, 0, canvas.getWidth()-1, canvas.getHeight()-1, paint);

        paint.setStyle(Style.STROKE);
        paint.setColor(0xff00ff00);            
        canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, 40, paint);

        paint.setStyle(Style.FILL);
        paint.setColor(0x770000ff);
        canvas.drawRect(100, 100, 200, 200, paint);
        invalidate();
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                         WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(new RenderView(this));
}
}

Here is a pic: 在此处输入图片说明

How should i proceed?

The problem is that the bounds of your rectangle are not depending on the screen size.

canvas.drawRect(100, 100, 200, 200, paint);

will draw in pixels.

What you need is an appropriate multiplier for the width, height, top and left. (float)(height / width) or (float)(width / height) - depending on wich is larger.

canvas.drawRect(leftOffset* ratio, topOffset * ratio, baseWidth * ratio, baseHeight * ratio, paint);

If you use real Bitmaps, you would also need to scale it to the correct size.

I think this code gets the apropriately sized bitmap:

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);

according to this post: Android - does decodeResource scale the bitmap for screen density?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM