Search code examples
androiddrawingrect

DrawArc on image, positioning issue


I have a drawable of a gauge and I try to draw a line on it. (Fixed position, not fixed value)

Unfortunately I don't have any experience with drawing. (And I think its hard to understand)

At the moment it looks like this: https://i.sstatic.net/5tkXEl.png

As you can see, its not positioned right and I'm quite afraid of looking at it on other devices.

Code (Class extends View):

private void init(Context context) {
    bounds = new Rect();
    gaugeBackground = ContextCompat.getDrawable(context, R.drawable.gauge);
    arcPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    arcPaint.setColor(Color.RED);
    arcPaint.setStyle(Paint.Style.STROKE);
    arcPaint.setStrokeWidth(7f);
}

protected void onDraw(Canvas canvas) {
    canvas.getClipBounds(bounds);
    gaugeBackground.setBounds(bounds);
    gaugeBackground.draw(canvas);

    float padding = 5;
    float size = getWidth() < getHeight() ? getWidth() : getHeight();
    float width = size - (2 * padding);
    float height = size - (2 * padding);
    float radius = (width < height ? width /2 : height /2);

    float rectLeft = (width /2) - radius + padding;
    float rectTop = (getHeight() /2) - radius + padding;
    float rectRight = (getWidth() /2) - radius + padding + width;
    float rectBottom = (getHeight() /2) - radius + padding + height;

    RectF mRect = new RectF(rectLeft, rectTop, rectRight, rectBottom);
    canvas.drawArc(mRect, 119f, 300f, false, arcPaint);
}

Can someone provide helpful information? I hope I finally get the whole RectF/Drawing stuff..


Solution

  • Oh well, I had multiple issues with my implementation.

    Main issue: The Background Image was 'warped', so the gauge wasn't really round.

    Also: The code was kind of messed up and way too complicated.

    I leave the question here - maybe it helps someone in the future.

    protected void onDraw(Canvas canvas) {
        canvas.getClipBounds(bounds);+
        //0.86 == Aspect Ratio of the Background
        gaugeBackground.setBounds(0, 0, bounds.right, (int) Math.round(bounds.bottom * 0.86));
        gaugeBackground.draw(canvas);
    
        float padding = 3;
        float size = getWidth() < getHeight() ? getWidth() : getHeight();
        float width = size - (2 * padding);
        float height = size - (2 * padding);
    
        RectF mRect = new RectF(padding, padding, width, height);
        canvas.drawArc(mRect, 134f, 271f, false, arcPaint);
    }