简体   繁体   中英

How to display image using canvas for all sizes

I'm doing app which display one image within the canvas. It's working well in one device, but if I run same app in another devices the image is not displaying correctly, because in this onDraw I did not mention imageview width or height,so any one can u suggest me how to give width and hight to that imageview in side onDraw method.

My code is:

@Override
public void onDraw(Canvas canvas) {
    Paint painto = new Paint();
    painto.setAntiAlias(true);
    painto.setColor(getResources().getColor(R.color.magnata));
    painto.setStrokeWidth(3);
    painto.setStyle(Paint.Style.FILL);
    Paint paint = new Paint();
    int leftx2 = (int) (10 * (screenWidth / 1024));
    int topy1 = (int) (10 * (screenHeight / 600));

    Bitmap kangoo = BitmapFactory.decodeResource(getResources(),
            R.drawable.kangoo);
    canvas.drawColor(Color.BLACK);
    canvas.drawBitmap(kangoo, leftx2, topy1, painto);
}

you can set the width and height by using the onSizeChange().This can give you the changing width and height

protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        // TODO Auto-generated method stub
        super.onSizeChanged(w, h, oldw, oldh);
         newwidth=w;
                 newheight=h;
    }

Try like this

@Override  
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            // TODO Auto-generated method stub
            super.onSizeChanged(w, h, oldw, oldh);
             newwidth=w;
                     newheight=h;
        }
@Override
    public void onDraw(Canvas canvas) {
        Paint painto = new Paint();
        painto.setAntiAlias(true);
        painto.setColor(getResources().getColor(R.color.magnata));
        painto.setStrokeWidth(3);
        painto.setStyle(Paint.Style.FILL);
        Paint paint = new Paint();
        int leftx2 = (int) (10 * (newwidth / 1024));
        int topy1 = (int) (10 * (newheight / 600));

        Bitmap kangoo = BitmapFactory.decodeResource(getResources(),
                R.drawable.kangoo);
        canvas.drawColor(Color.BLACK);
        canvas.drawBitmap(kangoo, leftx2, topy1, painto);
    }

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