public class RoundImageView extends ImageView {
...
}
2. 角丸の黒い9patch画像もしくはshapeを用意する
res/drawable/mask.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<corners android:radius="32dp" />
<solid android:color="#000000" />
</shape>
3. onDraw()で SRC_ATOP を使ってくりぬく
public class RoundImageView extends ImageView {
Paint mMaskedPaint;
Paint mCopyPaint;
Drawable mMaskDrawable;
public RoundImageView(Context context) {
this(context, null);
}
public RoundImageView(Context context, AttributeSet attrs) {
super(context, attrs);
mMaskedPaint = new Paint();
mMaskedPaint.setXfermode(new PorterDuffXfermode(
PorterDuff.Mode.SRC_ATOP));
mCopyPaint = new Paint();
mMaskDrawable = getResources().getDrawable(R.drawable.mask);
}
Rect mBounds;
RectF mBoundsF;
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mBounds = new Rect(0, 0, w, h);
mBoundsF = new RectF(mBounds);
}
@Override
protected void onDraw(Canvas canvas) {
int sc = canvas.saveLayer(mBoundsF, mCopyPaint,
Canvas.HAS_ALPHA_LAYER_SAVE_FLAG
| Canvas.FULL_COLOR_LAYER_SAVE_FLAG);
mMaskDrawable.setBounds(mBounds);
mMaskDrawable.draw(canvas);
canvas.saveLayer(mBoundsF, mMaskedPaint, 0);
super.onDraw(canvas);
canvas.restoreToCount(sc);
}
}
4. カスタムビューとして使う
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<com.example.roundimage.RoundImageView
android:layout_width="96dp"
android:layout_height="96dp"
android:src="@drawable/image1" />
</RelativeLayout>