童鞋们,你还在为绘制常用的多边形而烦恼吗?不用怕,小福利,有需要的尽管拿去!
ShapeView,支持圆、三角形、正方形、五边形、五角星、六边形。
效果图:
代码
attr.xml
<declare-styleable name="ShapeView">
<attr name="sv_color" format="color|reference" />
<attr name="sv_stroke_width" format="dimension" />
<attr name="sv_style">
<enum name="fill" value="0" />
<enum name="stroke" value="1" />
</attr>
<attr name="sv_shape">
<enum name="circle" value="0" />
<enum name="triangle" value="1" />
<enum name="rectangle" value="2" />
<enum name="pentagon" value="3" />
<enum name="pentagram" value="4" />
<enum name="sexangle" value="5" />
</attr>
</declare-styleable>
view源码:
ShapeView.java
package exam.org.jsc.password.view;
import android.content.Context;
import android.content.res.TypedArray;
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 exam.org.jsc.password.R;
/**
* Created by Justin Qin on 3/25/2017.
*/
public class ShapeView extends View {
Paint mPaint;
int color;
int strokeWidth;
int viewShape;
int paintStyle;
private static final ViewShape[] sShapeArray = {
ViewShape.CIRCLE,
ViewShape.TRIANGLE,
ViewShape.RECTANGLE,
ViewShape.PENTAGON,
ViewShape.PENTAGRAM,
ViewShape.SEXANGLE,
};
private static final PaintStyle[] sStyleArray = {
PaintStyle.FILL,
PaintStyle.STROKE
};
enum ViewShape {
/**圆*/
CIRCLE (0),
/**三角形*/
TRIANGLE (1),
/**四边形*/
RECTANGLE (2),
/**五边形*/
PENTAGON (3),
/**五角星*/
PENTAGRAM (4),
/**六边形*/
SEXANGLE (5);
ViewShape(int shape) {
this.shape = shape;
}
final int shape;
}
enum PaintStyle {
FILL (0),
STROKE (1);
PaintStyle(int style) {
this.style = style;
}
final int style;
}
public ShapeView(Context context) {
this(context, null);
}
public ShapeView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ShapeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ShapeView);
color = array.getColor(R.styleable.ShapeView_sv_color, Color.TRANSPARENT);
strokeWidth = array.getDimensionPixelSize(R.styleable.ShapeView_sv_stroke_width, 2);
viewShape = array.getInt(R.styleable.ShapeView_sv_shape, 0);
paintStyle = array.getInt(R.styleable.ShapeView_sv_style, 0);
array.recycle();
init();
}