LayerDrawable,setLayerInset的奇怪行为

时间:2013-04-11 13:34:09

标签: android shapedrawable

我正在尝试使用具有2层的LayerDrawable以编程方式为ImageButton创建Drawable。这些图层是ShapeDrawables。一个代表按钮表面,其尺寸与按钮的尺寸相匹配。第二个是按钮上的标志,它小于按钮。以一个停止按钮为例。

我正在尝试使用setIntrinsicWidth / setIntrinsicHeight和setLayerInset的组合将符号放入按钮中心,但是我得到了一个奇怪的结果。

public Drawable createStopButtonDrawable(int width, int height) {
    //-- width = 60, height = 30
    ShapeDrawable button = new ShapeDrawable(new RectShape());      
    button.setIntrinsicHeight(height);
    button.setIntrinsicWidth(width);
    button.setShaderFactory(new ShapeDrawable.ShaderFactory() {         
        @Override
        public Shader resize(int width, int height) {
            return new LinearGradient(0, 0, 0, height, 
                    new int[]{0xCDCCCCCC, 0xCDFFFFFF, 0xCDCCCCCC}, 
                    new float[]{0, 0.3f, 1},
                    Shader.TileMode.REPEAT);
        }
    });


    ShapeDrawable sign = new ShapeDrawable(new RectShape());
    int signSize = (int)(STOP_SIGN_SIZE_RATIO * (float)Math.min(width, height));
    //-- signSize = 12
    sign.setIntrinsicHeight(signSize);
    sign.setIntrinsicWidth(signSize);
    Paint psPaint = sign.getPaint();
    psPaint.setStyle(Style.FILL);
    psPaint.setColor(PLAY_BUTTON_SIGN_COLOR);

    Drawable[] layers = new Drawable[]{ button, sign };
    LayerDrawable ld = new LayerDrawable(layers);
    ld.setBounds(0, 0, width, height);
    ld.setLayerInset(0, 0, 0, 0, 0);

    int sx = (int)( (width - signSize)/2.0f );
    //-- sx = 24
    int sy = (int)( (height - signSize)/2.0f );
    //-- sy = 9

    ld.setLayerInset(1, sx, sy, sx, sy);   //-- 1. Sign stretched
    //ld.setLayerInset(1, sx, 10, sx, 9);  //-- 2. Almost good
    return ld;
}

这会生成按钮,其符号拉伸以匹配按钮大小。

Sign stretched

但是,如果我将“1. Sign stretched”替换为“2.几乎好”,我几乎得到了预期的结果。

Sign is almost right

我做错了什么?

我也注意到显示的按钮表面尺寸为59x29,而不是预期的60x30。

0 个答案:

没有答案