문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top