简体   繁体   中英

Java Android stretch Bitmap/PNG by width but keep height

I have a png image resource that I am making into a Canvas, then drawing another png resource (an arrow) on top of it. I am wondering how I can stretch this arrow by width and keep height the same? All methods I've tried have resulted in parts of the arrow cut off or other errors. Below I have pasted the current attempt however arrow3 (scaled to be wider and shorter than the original) is taller and wider than the original with part of the arrow cut off on the top and bottom. All help is appreciated

   Bitmap fieldBitmapResource = BitmapFactory.decodeResource(getResources(),
            R.drawable.football_field);
    Bitmap fieldBitmap = fieldBitmapResource.copy(null, true);
    Canvas fieldCanvas = new Canvas(fieldBitmap);

    Bitmap arrowBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.back);
    fieldCanvas.drawBitmap(arrowBitmap, 0, 0, null); //draw arrow to field

    Bitmap arrow2 = scaleCenterCrop(arrowBitmap, 150, 155);
    fieldCanvas.drawBitmap(arrow2, 1025, 573, null);

    Bitmap arrow3 = scaleCenterCrop(arrowBitmap, 150, 400);
    fieldCanvas.drawBitmap(arrow3, 1200, 600, null);

    ...

    public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
int sourceWidth = source.getWidth();
int sourceHeight = source.getHeight();

// Compute the scaling factors to fit the new height and width, respectively.
// To cover the final image, the final scaling will be the bigger
// of these two.
float xScale = (float) newWidth / sourceWidth;
float yScale = (float) newHeight / sourceHeight;
float scale = Math.max(xScale, yScale);

// Now get the size of the source bitmap when scaled
float scaledWidth = scale * sourceWidth;
float scaledHeight = scale * sourceHeight;

// Let's find out the upper left coordinates if the scaled bitmap
// should be centered in the new size give by the parameters
float left = (newWidth - scaledWidth) / 2;
float top = (newHeight - scaledHeight) / 2;

// The target rectangle for the new, scaled version of the source bitmap will now
// be
RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);

// Finally, we create a new bitmap of the specified size and draw our new,
// scaled bitmap onto it.
Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
Canvas canvas = new Canvas(dest);
canvas.drawBitmap(source, null, targetRect, null);

return dest;

}

我建议调查9个补丁映像: http : //tekeye.biz/2012/android-9patch-files

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