简体   繁体   中英

Layout Background partially transparent

I want to set a transparent background. Maybe 20% of gray but i also want to have a small part of the background being completely transparent (a rectangle or a circle in the layout):

在此处输入图片说明

Is that possible? later i want the rectangle (or the circle) to be moveable and scaleable.

This is easily achievable with a custom drawable like this:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:innerRadius="0dp"
       android:shape="rectangle"
       android:thicknessRatio="1.9"
       android:useLevel="false">

    <solid android:color="@android:color/transparent"/>

    <stroke
        android:width="125dp"
        android:color="#CC000000"/>
</shape>

When you overlay that drawable on top of an image the results would looks something like this:

在此处输入图片说明

By creating that drawable dynamically in code you can adjust it at runtime. For example:

ShapeDrawable drawable = new ShapeDrawable(new RectShape());
drawable.getPaint().setColor(0xCC000000);
drawable.getPaint().setStyle(Paint.Style.STROKE);
drawable.getPaint().setStrokeWidth(dpToPixel(125.0f));
someView.setBackground(drawable);

You can influence the shape of the hole in the middle by combining multiple layers in a LayerDrawable .

You can also influence the general shape of the hole by setting the android:shape tag of the <shape /> element in the custom drawable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM