1.创建和初始化ShapeView
public class ShapeView extends View {
private Shape mCurrentShape = Shape.Circle;
Paint mPaint;
private Path mPath;
public ShapeView(Context context) {
this(context,null);
}
public ShapeView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public ShapeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPaint = new Paint();
mPaint.setAntiAlias(true);
}
public enum Shape {
Circle, Square, Triangle
}
2.onMeasure()
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 只保证是正方形
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(Math.min(width, height), Math.min(width, height));
}
3.onDraw()
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
switch (mCurrentShape) {
case Circle:
//画圆形
int center = getWidth() / 2;
mPaint.setColor(Color.YELLOW);
canvas.drawCircle(center, center, center, mPaint);
break;
case Square:
//画正方形
mPaint.setColor(Color.BLUE);
canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
break;
case Triangle:
// 画三角 Path 画路线
mPaint.setColor(Color.RED);
if (mPath == null) {
// 画路径
mPath = new Path();
mPath.moveTo(getWidth() / 2, 0);
mPath.lineTo(0, (float) ((getWidth()/2)*Math.sqrt(3)));
mPath.lineTo(getWidth(), (float) ((getWidth()/2)*Math.sqrt(3)));
// path.lineTo(getWidth()/2,0);
mPath.close();// 把路径闭合
}
canvas.drawPath(mPath, mPaint);
break;
}
}
4.测试
public void exchange() {
switch (mCurrentShape) {
case Circle:
mCurrentShape = Shape.Square;
break;
case Square:
mCurrentShape = Shape.Triangle;
break;
case Triangle:
mCurrentShape = Shape.Circle;
break;
}
invalidate();
}
<!-- 58同城数据加载-->
<com.itjs.myapplication.ShapeView
android:id="@+id/shape_view"
android:layout_width="30dp"
android:layout_height="30dp" />
<Button
android:layout_width="wrap_content"
android:onClick="exchange"
android:text="切换"
android:layout_height="wrap_content" />
public void exchange(View view) {
new Thread(
new Runnable() {
@Override
public void run() {
while (true) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mShapeView.exchange();
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
).start();
}