Drawing a filled rectangle with a border in android

后端 未结 3 1037
忘掉有多难
忘掉有多难 2020-12-08 18:43

Is there any way in Android to draw a filled rectangle with say a black border. My problem is that the canvas.draw() takes one paint object, and to my knowledge the paint ob

3条回答
  •  被撕碎了的回忆
    2020-12-08 18:53

    If you are drawing multiple views then you could also use two paints, one for the stroke and one for the fill. That way you don't have to keep resetting them.

    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
    }
    

提交回复
热议问题