58

Android中有什么方法可以绘制一个带有黑色边框的填充矩形。我的问题是 canvas.draw() 需要一个绘画对象,据我所知,绘画对象不能为填充和描边使用不同的颜色。有没有解决的办法?

4

3 回答 3

152

试试油漆。setStyle (Paint.Style.FILL )和绘画。设置样式(Paint.Style.STROKE

Paint paint = new Paint();
Rect r = new Rect(10, 10, 200, 100);

@Override
public void onDraw(Canvas canvas) {
    // fill
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.MAGENTA); 
    canvas.drawRect(r, paint);

    // border
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(Color.BLACK);
    canvas.drawRect(r, paint);
}
于 2013-08-24T09:51:26.530 回答
49

如果您正在绘制多个视图,那么您还可以使用两种颜料,一种用于描边,一种用于填充。这样您就不必一直重置它们。

在此处输入图像描述

Paint fillPaint = new Paint();
Paint strokePaint = new Paint();

RectF r = new RectF(30, 30, 1000, 500);

void initPaints() {

    // fill
    fillPaint.setStyle(Paint.Style.FILL);
    fillPaint.setColor(Color.YELLOW);

    // stroke
    strokePaint.setStyle(Paint.Style.STROKE);
    strokePaint.setColor(Color.BLACK);
    strokePaint.setStrokeWidth(10);
}

@Override
protected void onDraw(Canvas canvas) {

    // First rectangle
    canvas.drawRect(r, fillPaint);    // fill
    canvas.drawRect(r, strokePaint);  // stroke

    canvas.translate(0, 600);

    // Second rectangle
    int cornerRadius = 50;
    canvas.drawRoundRect(r, cornerRadius, cornerRadius, fillPaint);    // fill
    canvas.drawRoundRect(r, cornerRadius, cornerRadius, strokePaint);  // stroke
}
于 2017-05-16T12:21:36.763 回答
1

您用边框的颜色和矩形加上边框的大小绘制一个矩形,您更改油漆的颜色并再次绘制具有正常大小的矩形。

于 2012-11-24T21:32:04.697 回答