简体   繁体   中英

Aligning an image in an ImageView to the top-right corner

There is the ImageView which has larger size than the image. How can I align the image in top-right (and bottom-left) corner of the control?

PS I know about the parameter scaleType . Its values fitStart and fitEnd are not suitable in this case, because they align image in opposite corners.

scaleType cannot let you align view in top-right or bottom-left corner, but layout_gravity will.

...
<FrameLayout android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="start|bottom" 
        android:src="@drawable/your_drawable"/>
</FrameLayout>
...

Change layout_gravity accordingly base on your needs:
bottom-left: start|bottom
top-right: top|end

It's simpler to use layout_gravity to align views. If you don't like, you can use ImageView & matrix this way:

private void alignTopRight(ImageView imageView)
{
    imageView.setScaleType(ImageView.ScaleType.MATRIX); // !

    final int drawableWidth = imageView.getDrawable().getIntrinsicWidth();
    final int viewWidth = imageView.getWidth();
    Matrix matrix = new Matrix();
    matrix.postTranslate(viewWidth-drawableWidth, 0);
    imageView.setImageMatrix(matrix);
}

private void alignBottomLeft(ImageView imageView)
{
    imageView.setScaleType(ImageView.ScaleType.MATRIX); // !

    final int drawableHeight = imageView.getDrawable().getIntrinsicHeight();
    final int viewHeight = imageView.getHeight();
    Matrix matrix = new Matrix();
    matrix.postTranslate(0, viewHeight-drawableHeight);
    imageView.setImageMatrix(matrix);
}

The easiest way would probably be to not use an image view and make a custom view that does what you want. That's pretty trivial. Short of that, use scaletype matrix and create a matrix that translates and scales appropriately.

This worked for me:

image.scaleType = ImageView.ScaleType.FIT_START

This is the easiest way to do it! Hope you find it well too

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