Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How can I set my custom surfaceview to a fixed size ratio in xml?

I am trying to have a surfaceview (a custom class which extends surfaceview) that I add in the xml layout to have a fixed size ratio: 4:3 (length to width).

I want it to fill as much as it can of it's parent, either on the length or width but once it reaches the full length or width it will adjust the other side to have a fixed size ratio like I said before.

How can I achieve such a thing?

Thanks.

like image 531
Daniel Mendel Avatar asked Oct 26 '12 07:10

Daniel Mendel


2 Answers

In the onCreate method of your activity you could read the resolution of the screen and set the layout width and height to it.

Example assuming you're using RealtiveLayout:

private void create43RatioSurface() {
    SurfaceView surfaceView43 = (SurfaceView)findViewById(R.id.surfaceView1);

    DisplayMetrics metrics = getResources().getDisplayMetrics();
    int height = 0;
    int width = 0;

    if(metrics.widthPixels < metrics.heightPixels){
        width = metrics.widthPixels;
        height= (metrics.widthPixels/4) * 3 ;
    } else {
        height= metrics.heightPixels;
        width= (metrics.heightPixels/4) * 3 ;
    }

    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width, height);
    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);

    surfaceView43.setLayoutParams(layoutParams);        
}
like image 70
Bruno Bieri Avatar answered Oct 20 '22 10:10

Bruno Bieri


This might be kind of hacky but you could maybe put a blank imageview as a sort of frame for the surfaceview. Now to explain the madness

1)Create an image asset that fits the proportion you want that is all transparent. Lets call tis our ghost image (probably best to make it invisible as well)

2)use a relative layout and place the imageview in the relative layout with match_parent for height and width and using scaletype CENTER_INSIDE or CENTER_CROP if you went van gocha and created a massive asset

3)add your surface view to the layout after the imageview and aligntop/bottom/right/left with the image view

I haven't tried this implementation but it should give you the ratio you want for whatever screen you have.

like image 24
MikeIsrael Avatar answered Oct 20 '22 10:10

MikeIsrael