android_studio的canvas畫圓
阿新 • • 發佈:2018-12-01
1.怎樣設定程式碼
package com.example.rk1130;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/*
自定義view
*/
public class BallView extends View {
private String ball_size;
private float tx=200f;
private float ty=200f;
private Paint paint;
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(){ //設定畫筆 paint = new Paint(); //顏色 paint.setColor(Color.BLUE); //抗鋸齒 paint.setAntiAlias(true); //畫筆粗細 paint.setStrokeWidth(2); //填充 paint.setStyle(Paint.Style.FILL); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Path path=new Path(); canvas.drawCircle(tx,ty,50,paint); } @Override public boolean onTouchEvent(MotionEvent event) { //兩種方式 一種switch 一種直接寫 switch (event.getAction()){ case MotionEvent.ACTION_UP: tx=event.getX(); ty=event.getY(); break; case MotionEvent.ACTION_DOWN: tx=event.getX(); ty=event.getY(); break; case MotionEvent.ACTION_MOVE: tx=event.getX(); ty=event.getY(); break; } /*tx=event.getX(); ty=event.getY();*/ this.invalidate(); return true; }
}
2.佈局
<?xml version="1.0" encoding="utf-8"?><com.example.rk1130.BallView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>