如何用黑色填充我的自定义视图,但在中心将是透明圆圈?

时间:2015-04-23 09:10:15

标签: android canvas

如何用黑色填充我的自定义视图,但中心的透明圆圈是什么?不使用位图。

感谢。

3 个答案:

答案 0 :(得分:0)

此代码可以帮助您

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }

    public class MyView extends View {
        public MyView(Context context) {
            super(context);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            int x = getWidth();
            int y = getHeight();
            int radius;
            radius = 100;
            Paint paint = new Paint();
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.WHITE);
            canvas.drawPaint(paint);
            // Use Color.parseColor to define HTML colors
            paint.setColor(Color.parseColor("#CD5C5C"));
            canvas.drawCircle(x / 2, y / 2, radius, paint);
        }
    }
}

enter image description here

最终更新

这是黑色背景: paint.setColor(Color.BLACK);

enter image description here

答案 1 :(得分:0)

它的drawable,设置为您查看的背景。但圆圈不透明。也许你可以设置你想要的圆圈颜色。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">


    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">
            <solid android:color="#000" />
        </shape>

    </item>

    <item>

        <shape
            android:innerRadius="50dp"
            android:shape="ring">
            <solid android:color="#FFF" />
        </shape>

    </item>
</layer-list>

答案 2 :(得分:0)

您使用 xfermod 和透明颜色创建透明效果涂料

clearPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
clearPaint.color = ResourcesCompat.getColor(resources, R.color.transparent, null)

您还需要从视图中禁用硬件加速器

view.setLayerType(View.LAYER_TYPE_SOFTWARE, null)

我给你一个自定义视图的例子:

class MyCustomView(context: Context) : View(context) {
    private val paint: Paint by lazy { Paint() }
    private lateinit var clearPaint: Paint
    
    init {      
        clearPaint = Paint()
        clearPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
    }

    public override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        //draw blackbackground
        paint.color = ResourcesCompat.getColor(resources, R.color.black, null)
        canvas.drawPaint(paint)

        val circleRadius: Float = parent.height.toFloat() / 8  //example radius
        clearPaint.color = ResourcesCompat.getColor(resources, R.color.transparent, null)
        //circle
        canvas.drawCircle(parent.width.toFloat() / 2, parent.height.toFloat() / 2, circleRadius, clearPaint)
    }    
}

(Kotlin 解决方案)