Search code examples
androidandroid-imageviewscaleaspect-ratioandroid-constraintlayout

How to set imageview in Percent Relative Layout to following ratio's based on device screen size ,16:9,1:1,3:2,2:1,4:3


I have an imageview to display an image and i want to enable the option to crop the image using the following ratio's 16:9,1:1,3:2,2:1,4:3 .I have some buttons for each ,so user can crop the image in to the following by clicking a button. How to do this based on devices with varying screen sizes.

I got the device screen height and width using the following code snippet

  DisplayMetrics displaymetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
            int height = displaymetrics.heightPixels;
            int width = displaymetrics.widthPixels;

and i can set the width and height to imageview using this snippet

  FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
            params.height=height;
            params.width=width;
            touchImageView.setLayoutParams(params);

But how to do this with Percent Relative Layout (16:9,1:1,3:2,2:1,4:3)

can anyone help ??


Solution

  • You can use Percent Relative Layout

    http://developer.android.com/reference/android/support/percent/PercentRelativeLayout.html

    private void changeAspectRatio(int width, int height, Float ratio, PercentRelativeLayout mPercentRelativeLayout) {
        PercentRelativeLayout.LayoutParams layoutParamsMain = new PercentRelativeLayout.LayoutParams(getApplicationContext(), null);
        if (width != 0)
            layoutParamsMain.width = width;
        if (height != 0)
            layoutParamsMain.width = width;
        PercentLayoutHelper.PercentLayoutInfo info1 = layoutParamsMain.getPercentLayoutInfo();
        if (ratio != 0f)
            info1.aspectRatio = ratio;
        mPercentRelativeLayout.setLayoutParams(layoutParamsMain);
        mPercentRelativeLayout.requestLayout();
    }
    
    
    changeAspectRatio((int)(width*.9), 0, 1.77f, mPercentRelativeLayout);
    
    to get 16:9 , 16/9 = 1.77 and pass this value like above function call.
    

    Then it will set 16:9 aspect ratio.