通过动态设置高度来裁剪图像

时间:2017-12-04 06:34:35

标签: android

猜猜一张男人的照片。 (头顶部和底部腿部):P

我使用layoutparam动态设置高度。

当我为例如300设置高度时,

它将HEAD的高度设置为300个单位,朝向图像的腿。

我想要的是将高度从LEG设置为前300个单位。

imageView.setHeight()

1 个答案:

答案 0 :(得分:1)

在java类中使用此方法:

findOne

现在,如何称呼这个方法:

private void scaleImage(ImageView view) throws NoSuchElementException {
    // Get bitmap from the the ImageView.
    Bitmap bitmap = null;

    try {
        Drawable drawing = view.getDrawable();
        bitmap = ((BitmapDrawable) drawing).getBitmap();
    } catch (NullPointerException e) {
        throw new NoSuchElementException("No drawable on given view");
    } catch (ClassCastException e) {
        // Check bitmap is Ion drawable
//          bitmap = Ion.with(view).getBitmap();
    }

    // Get current dimensions AND the desired bounding box
    int width = 0;

    try {
        width = bitmap.getWidth();
    } catch (NullPointerException e) {
        throw new NoSuchElementException("Can't find bitmap on given view/drawable");
    }

    int height = bitmap.getHeight();
    int bounding = dpToPx(150);// set height
    Logger.i("Test", "original width = " + Integer.toString(width));
    Logger.i("Test", "original height = " + Integer.toString(height));
    Logger.i("Test", "bounding = " + Integer.toString(bounding));

    // Determine how much to scale: the dimension requiring less scaling is
    // closer to the its side. This way the image always stays inside your
    // bounding box AND either x/y axis touches it.
    float xScale = ((float) bounding) / width;
    float yScale = ((float) bounding) / height;
    float scale = (xScale <= yScale) ? xScale : yScale;
    Logger.i("Test", "xScale = " + Float.toString(xScale));
    Logger.i("Test", "yScale = " + Float.toString(yScale));
    Logger.i("Test", "scale = " + Float.toString(scale));

    // Create a matrix for the scaling and add the scaling data
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Create a new bitmap and convert it to a format understood by the ImageView
    Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    width = scaledBitmap.getWidth(); // re-use
    height = scaledBitmap.getHeight(); // re-use
    BitmapDrawable result = new BitmapDrawable(scaledBitmap);
    Logger.i("Test", "scaled width = " + Integer.toString(width));
    Logger.i("Test", "scaled height = " + Integer.toString(height));

    // Apply the scaled bitmap
    view.setImageDrawable(result);

    // Now change ImageView's dimensions to match the scaled image
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);

    Logger.i("Test", "done");
    }

    private int dpToPx(int dp) {
    float density = getApplicationContext().getResources().getDisplayMetrics().density;
    return Math.round((float) dp * density);
    }