Android canvas画圆

布局
android:id="@+id/ballView2"
android:layout_width=“match_parent”
android:layout_height=“wrap_content” />

BallView页面
package com.lll.day03;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class BallView extends View {

private Paint mRectPaint;
private float cx = 200f;
private float cy = 200f;

public BallView(Context context) {
    super(context);
    init();
}

public BallView(Context context,AttributeSet attrs) {
    super(context, attrs);
    init();
}

public BallView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init() {
     //创建画笔
    mRectPaint = new Paint();
    //设置画笔颜色
    mRectPaint.setColor(Color.GREEN);
    mRectPaint.setStrokeWidth(3);
    //设置画笔的样式
    mRectPaint.setStyle(Paint.Style.FILL);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
  //  Path path = new Path();
    canvas.drawCircle(cx,cy,50,mRectPaint);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
 //第一种简单方法

// cx = event.getX();
// cy = event.getY();
// this.invalidate();
//第二种判断
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
cx = event.getX();
cy = event.getY();
break;
case MotionEvent.ACTION_MOVE:
cx = event.getX();
cy = event.getY();
break;
case MotionEvent.ACTION_UP:
cx = event.getX();
cy = event.getY();
break;
}
this.invalidate();
return true;

}

}
MainActivity页面
package com.lll.day03;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

}

你可能感兴趣的:(Android canvas画圆)