LoginSignup
24
26

More than 5 years have passed since last update.

画像を丸角表示する方法

Last updated at Posted at 2013-12-14

画像を丸角にするやり方をググると多く出てくるのが、元のBitmapから新しい丸角Bitmapを生成してImageViewにセットする方法です。
Bitmapを加工するのではなく表示だけ丸角にした方が仕様変更にも対応しやすいし、Bitmap関連のメモリ意識や、キャッシュ戦略などへの関連性が低くなるので便利だろーと思います。

仕込み

参考1
http://stackoverflow.com/questions/12675161/bitmap-repeat-rounded-corners

参考1の参考元
http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners/

参考1のCurvedAndTiledを参考にした丸角描画用のDrawableクラスを作成します。

RoundDrawable.java

public class RoundDrawable extends Drawable{
    private final float mCornerRadius;
    private final RectF mRect = new RectF();
    private final BitmapShader mBitmapShader;
    private final Paint mPaint;

    public RoundDrawable(Bitmap bitmap, float cornerRadius) {
        mCornerRadius = cornerRadius;

        mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,Shader.TileMode.CLAMP);

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setShader(mBitmapShader);
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        super.onBoundsChange(bounds);
        mRect.set(0, 0, bounds.width(), bounds.height());
    }

    @Override
    public void draw(Canvas canvas) {
        canvas.drawRoundRect(mRect, mCornerRadius, mCornerRadius, mPaint);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    @Override
    public void setAlpha(int alpha) {
        mPaint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        mPaint.setColorFilter(cf);
    }
}

使い方

Drawableの拡張なので使い道はたくさんです。
BitmapをImageViewで丸角表示させる場合の例

float cornerRadius = 6.f;
Drawable roundDrawable = new RoundDrawable(bitmap , cornerRadius);
imageView.setImageDrawable(roundDrawable);

おしまい

追記

ImageViewでscaleTypeが反映されない問題がありました。
ImageViewのソースを見てみるとBitmapDrawableを生成していたので、そっちで拡張してうまい具合にできないかなーとごにょごにょしてみるも、ごにょりきれず。

そんな矢先に名前がまんまのライブラリを発見。
https://github.com/vinc3m1/RoundedImageView

コードがシンプルで使い方も簡単でボーダーも引けるようなのでコレ良いですねっていうライブラリ紹介オチでした。

24
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
26