ImageView丸くする

TODO:検証する

Material Designとか出てImageView丸くしたい場合があると思う。

パフォーマンスは置いといて実装するだけならいくつかやり方ありそう。

XML

なんでもいいけど適当にShape作ってImageViewに被せる。描画コストがかかるのであんまりよくなさそう。

circle_corners.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners 
        android:radius="30dp" />
    <stroke 
        android:color="#ffffffff"
        android:width="10dp" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/image_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:padding="5dp"
        android:scaleType="centerCrop" />

    <ImageView
        android:id="@+id/img_corners"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:src="@drawable/circle_corners" />

</RelativeLayout>

Java

Bitmap作ってImageViewに渡す。

public class ImageHelper {
    public static Bitmap getRoundedBitmap(final Bitmap source) {
        int size = Math.min(source.getWidth(), source.getHeight());

        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;

        Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
        if (squaredBitmap != source) {
            source.recycle();
        }

        Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
        paint.setShader(shader);
        paint.setAntiAlias(true);

        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);

        squaredBitmap.recycle();
        return bitmap;
    }
}

Libary

要件を満たすのであればライブラリを使っても良さそう。

結論

XMLだけで書くのは試してみる場合とかはいいけどプロダクトに入れるなら自前でジャバを書いてCanvas上で円を描画するか既存のライブラリ入れるのが良さそう。というか他にも実装の仕方色々あると思う。