Android LinearGradient and weird relative positioning

I have the following code with LinearGradient, which looks the same as all other examples.

public class CustomColourBar extends View
{

public CustomColourBar( Context context, AttributeSet attribs )
{
    super( context, attribs );
}    

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    setMeasuredDimension(170, 40);
}

@Override
protected synchronized void onDraw( Canvas canvas )
{
    int height = this.getMeasuredHeight();
    int width = this.getMeasuredWidth();

    LinearGradient shader = new LinearGradient(
        0, 0, 0, height, 
        Color.RED, Color.YELLOW,
        Shader.TileMode.CLAMP );

    Paint paint = new Paint(); 
    paint.setShader(shader);
    RectF fgRect = new RectF( 0, 0, width, height);

    canvas.drawRoundRect(fgRect, 7f, 7f, paint);

}
}

In the layout, this leads to the following, which roughly corresponds to the rule:

http://i.stack.imgur.com/Pqbx1.png

However, when other things change the Y position of my view, this happens incorrectly:

http://i.stack.imgur.com/bnyeU.png

LinearGradient uses the absolute position relative to the top view (i.e. the dialog box). I can’t understand for life why?

Thank!

Rob

+3
source share
2 answers

I had the same problem. The positions in the shader are not shapes, but the canvas is relative.

Therefore, you need to draw your figures on the canvas always around the original and translate the canvas with the desired position.

For instance:

NO NO:

canvas.drawCircle(posx, posy, radius);

DO:

canvas.save();
canvas.translate(posx, posy);
canvas.drawCircle(0,0,radius);
canvas.restore();

, !;)

+7

Android , , , configChanges

0

Source: https://habr.com/ru/post/1794849/


All Articles