Android不同形状切换
一、效果图

二、代码实现
2.1 java代码
package com.example.layoutdemo.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class ShapeView extends View {
private Paint mPaint;
private Path mPath;
private static final int SQUARE = 1;
private static final int CIRCLE = 2;
private static final int TRIANGLE = 3;
private int mType = SQUARE;
@IntDef({SQUARE,CIRCLE,TRIANGLE})
@Retention(RetentionPolicy.SOURCE)
private @interface ShareType{
}
public void setType(@ShareType int type) {
mType = type;
}
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.setDither(true);
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(10);
mPaint.setStyle(Paint.Style.FILL);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int size = widthSize > heightSize?heightSize:widthSize;
setMeasuredDimension(size,size);
}
@Override
protected void onDraw(Canvas canvas) {
int center = getWidth()/2;
switch (mType){
case SQUARE:
mPaint.setColor(Color.RED);
canvas.drawRect(0,0,getWidth(),getHeight(),mPaint);
break;
case CIRCLE:
mPaint.setColor(Color.BLUE);
canvas.drawOval(0,0,getWidth(),getHeight(),mPaint);
break;
case TRIANGLE:
mPaint.setColor(Color.BLACK);
if (mPath == null) {
mPath = new Path();
mPath.moveTo(center,0);
mPath.lineTo(0, (float) (center * Math.sqrt(3)));
mPath.lineTo(getWidth(),(float) (center * Math.sqrt(3)));
mPath.close();
}
canvas.drawPath(mPath,mPaint);
break;
}
}
public synchronized void start() {
if (mType == SQUARE) {
mType = CIRCLE;
} else if (mType == CIRCLE) {
mType = TRIANGLE;
} else {
mType = SQUARE;
}
postInvalidate();
}
}
2.2 控件使用
<com.example.layoutdemo.widget.ShapeView
android:id="@+id/shape_view"
android:layout_margin="20dp"
android:layout_width="200dp"
android:layout_height="200dp"/>
final ShapeView shape_view= findViewById(R.id.shape_view);
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
shape_view.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
三、源码下载地址
Android自定义View