Crop Bitmap image to custom sguare

Image sample I have this method written for cropping my image, but HEIGHT dimension doesnt work on the cropping, only weight is done right. I cant find the issue. I want to use my screen width and height as a dynamic width and height.

public Bitmap cropToSquare(Bitmap bitmap){
        int width  = mScreenWidth ;
        int height = mScreenHeight;
        int newWidth = width - 2 * 10;
        int newHeight = (height- newWidth) / 2;

        Bitmap cropImg = Bitmap.createBitmap(bitmap, 0, 0, newWidth, newHeight);
        return cropImg; }

    }

Upvotes: 0

Views: 39

Answers (1)

Walter Palladino
Walter Palladino

Reputation: 479

Here is my solution:

public static Bitmap getResizedClippedBitmap (Bitmap bm, int newWidth, int newHeight) {

    Bitmap targetBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(targetBitmap);

    float originalWidth = bm.getWidth();
    float originalHeight = bm.getHeight();

    float scale, xTranslation = 0.0f, yTranslation = 0.0f;
    if (originalWidth > originalHeight) {
        scale = newHeight/originalHeight;
        xTranslation = (newWidth - originalWidth * scale)/2.0f;
    }
    else {
        scale = newWidth / originalWidth;
        yTranslation = (newHeight - originalHeight * scale)/2.0f;
    }

    Matrix transformation = new Matrix();
    transformation.postTranslate(xTranslation, yTranslation);
    transformation.preScale(scale, scale);

    Paint paint = new Paint();
    paint.setFilterBitmap(true);
    canvas.drawBitmap(bm, transformation, paint);

    return targetBitmap;
}

You can find some other utils here: BitmapUtils.java Hope it helps.

Upvotes: 0

Related Questions