Android视图背景色与透明元素

时间:2013-11-13 10:42:40

标签: android view background transparent shape

我们可以轻松地使背景透明&像这样的形状的彩色元素:

  • 颜色:纯色
  • 白色/灰色方块:透明

enter image description here

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <corners 
        android:radius="20dp"/>
    <solid 
        android:color="#1f93ed" />
</shape>

但是我怎么能用这样的彩色背面和透明元素来制作视图背景:

enter image description here

好像背景颜色被表格遮住了...... 有什么想法吗?

3 个答案:

答案 0 :(得分:2)

您可以在自定义可绘制或视图中覆盖onDraw来绘制自己的彩色区域。

例如,在此代码中我绘制了四个“角轮廓”:

@Override
    protected void onDraw(Canvas canvas) 
    {
        super.onDraw(canvas);
        drawCorner(cornerSizeInPixel, canvas, Color.GREEN));
    }

    private void drawCorner(int size, Canvas canvas, int color)
    {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(color);
        paint.setStyle(Style.FILL);

        // top left
        Path p = new Path();
        p.moveTo(0, 0);
        p.lineTo(size, 0);
        p.arcTo(new RectF(0, 0, size, size), 180, 90, true);
        p.lineTo(0, 0);
        canvas.drawPath(p, paint);  

        // bottom left
        int h = canvas.getHeight();
        p = new Path();
        p.moveTo(0, h);
        p.lineTo(size, h);
        p.arcTo(new RectF(0, h - size, size, h), 90, 90, true);
        p.lineTo(0, h);
        canvas.drawPath(p, paint);

        // top right
        int w = canvas.getWidth();
        p = new Path();
        p.moveTo(w, 0);
        p.lineTo(w - size, 0);
        p.arcTo(new RectF(w - size, 0, w, size), 270, 90, true);
        p.lineTo(w, 0);
        canvas.drawPath(p, paint);  

        // bottom right
        p = new Path();
        p.moveTo(w, h);
        p.lineTo(w - size, h);
        p.arcTo(new RectF(w - size, h - size, w, h), 0, 90, true);
        p.lineTo(w, h);
        canvas.drawPath(p, paint);  
    }

结果:图像的每个角落都有4个绿色形状,它们一起绘制一个真正透明的圆角矩形

答案 1 :(得分:0)

android:color="#1f93ed"替换为android:color="@android:color/transparent,并将背景设置为蓝色

答案 2 :(得分:0)

选项1:使用普通的.png文件

选项2:通过扩展ShapeDrawable类

创建自定义Drawable