Domanda

We can easily make a background transparent & colored element with Shape like this :

  • Color bleue : Solid color
  • white/gray square : transparent

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>

But how can i do a view background with colored back and transparent element like this :

enter image description here

as if the background color was holed by form... Any idea?

È stato utile?

Soluzione

You can draw yourself colored area with override of onDraw in custom drawable or view.

For exemple, in this code i draw four "corner outline" :

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

Result: 4 green form in every corner of the image, which together draw a rounded rectangle really transparent

Altri suggerimenti

option 1: use normal .png file

option 2: create a custom Drawable by extending ShapeDrawable class

Replace android:color="#1f93ed" with android:color="@android:color/transparent and set the background to the Blue colour

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top