15
12

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.

使いやすいシンプルな円を描くView

Last updated at Posted at 2015-12-26

円を描きます!

xmlでやったり、Canvasを使うんでしょ・・・大きさの設定や位置の設定とか面倒だな・・・と思いきや、結構簡単なんです。
こんな感じ

public class CircleView extends View {
    private Paint paint;

    public CircleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
    }

    public CircleView(Context context) {
        super(context);
        paint = new Paint();
    }

    public void setColor(int color){
        paint.setColor(getResources().getColor(color));
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        paint.setAntiAlias(true);
        canvas.drawCircle(canvas.getHeight() / 2, canvas.getHeight() / 2, (canvas.getWidth() / 2) - 2, paint);
    }
}

外からsetColorで色も指定できます!
こんな感じに

circleView.setColor(R.color.white);

onDrawでcanvas.drawCircleを使い円を描きます。
これは、自分自身の大きさを取得し、Viewの真ん中に円を描く指定しています。これだけ

そしてこのクラスをlayoutを定義するxmlから以下のように設定し使います。

<test.ui.widget.CircleView
  android:id="@+id/circle_view"
  android:layout_width="48dp"
  android:layout_height="48dp" />
CircleView circleView = (CircleView) view.findViewById(R.id.circle_view);
circleView.setColor(R.color.black);

こうすると、48dp*48dpのViewの真ん中に黒い円が描かれます。
シンプルで汎用性高いと思います。

15
12
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
15
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?