开发者

Android LinearGradient and weird relative positioning

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

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);

}
}

I开发者_高级运维n a layout, this produces the following, which is just about correct:

Android LinearGradient and weird relative positioning

However, when other things change the Y position of my view, it goes wrong:

Android LinearGradient and weird relative positioning

The LinearGradient is using the absolute position relative to the topmost view (i.e. the dialog). I can't for the life of me figure out - why?

Thank you!

Rob


I had the same problem. Positions in the shader are not shape but canvas relative.

Therefore you need to draw your shapes on the canvas always around the origo and translate the canvas with the desired position.

For instance:

DO NOT:

canvas.drawCircle(posx, posy, radius);

DO:

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

Hope it helped! ;)


In the android manifest file, choose the activity you are using and make sure configChanges property of it has orientation ticked

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜