16
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AndroidでViewを「くり抜く」方法

Last updated at Posted at 2017-07-22

AndroidのAPIlevel1から提供されているcanvasを使う事によって、様々なViewの形を実現することができます。
一般的な使い方は、円や長方形などのViewの生成や、Bitmapの切り取りなどではないでしょうか?
そこで今回はViewをくり抜く方法について紹介したいと思います。

まずはViewを描画する方法

public class CanvasView extends View {

    private Paint paint = new Paint();

    public CanvasView(Context context) {
        super(context);
    }

    public CanvasView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CanvasView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(getRootView().getWidth() / 2, getRootView().getHeight() / 2, 50, paint);
    }
}

Viewをくり抜く方法

public class CanvasView extends View {

    private Paint backgroundPaint = new Paint();
    private Paint paint = new Paint();

    public CanvasView(Context context) {
        super(context);
    }

    public CanvasView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CanvasView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        setLayerType(View.LAYER_TYPE_HARDWARE, null);

        //全体を描画する
        backgroundPaint.setColor(ContextCompat.getColor(getContext(), android.R.color.background_dark));
        canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), backgroundPaint);

        //全体の背景から円をくり抜く
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, 250, paint);
    }
}

最後に

こちらで紹介した方法を使ってライブラリを作成しました。いいねと思った方はぜひスターをつけていただけるとうれしいです。

customTarget.gif

16
11
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
16
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?