我想制作一个自定义颜色框,可以包含一种或两种颜色(参见图片)
我听说过onDraw方法,但从来没有使用它,我也不知道如何从活动中做到这一点.. 任何可以给我一个从哪里开始的提示?
-Thanks
答案 0 :(得分:0)
这是我的代码:D Canvas
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
}
@Override
public void onDraw(Canvas canvas) {
paint.setColor(Color.BLACK);
paint.setStrokeWidth(3);
canvas.drawRect(30, 30, 80, 80, paint);
paint.setStrokeWidth(0);
paint.setColor(Color.CYAN);
canvas.drawRect(33, 60, 77, 77, paint );
paint.setColor(Color.YELLOW);
canvas.drawRect(33, 33, 77, 60, paint );
}
}
并在创建时添加此
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
答案 1 :(得分:0)
我找到了一个解决方案,这就是我最终的结果。将一个ArrayList of Colors作为参数,如果arraylist有多个颜色,则绘制两个三角形的颜色。如果不是,则使用第一种颜色制作正方形
public class ColorBox extends View {
Paint paint = new Paint();
String color1;
String color2;
public ColorBox(Context context, ArrayList<String> colors) {
super(context);
if(colors.size() == 1){
color1 = colors.get(0);
}
else{
color1 = colors.get(0);
color2 = colors.get(1);
}
}
@Override
public void onDraw(Canvas canvas) {
Point topLeft = new Point(7, 7);
Point topRight = new Point(7, 62);
Point bottomLeft = new Point(62, 7);
Point bottomRight = new Point(62, 62);
//This draw a thin line around the border, with line width 1
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1f);
canvas.drawRect(5, 5, 65, 65, paint);
paint.setColor(Color.parseColor(color1));
paint.setStrokeWidth(1);
paint.setStyle(Paint.Style.FILL);
if(color2 != null && !color2.isEmpty()) //Two Colors
{
//Draw Top Left Color
Path path1 = new Path();
path1.setFillType(Path.FillType.EVEN_ODD);
path1.moveTo(topLeft.x, topLeft.x);
path1.lineTo(topRight.x, topRight.y);
path1.lineTo(bottomLeft.x, bottomLeft.y);
path1.lineTo(topLeft.x, topLeft.y);
path1.close();
canvas.drawPath(path1, paint);
//Draw Bottom Right Color
paint.setColor(Color.parseColor(color2));
Path path2 = new Path();
path2.setFillType(Path.FillType.EVEN_ODD);
path2.moveTo(topRight.x, topRight.y);
path2.lineTo(bottomLeft.x, bottomLeft.y);
path2.lineTo(bottomRight.x, bottomRight.y);
path2.lineTo(topRight.x, topRight.y);
path2.close();
canvas.drawPath(path2, paint);
}
else {
canvas.drawRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y, paint);
}
}