The problem of clipPath failure caused by Android Canvas hardware acceleration

When customizing View, you can use Canvas to crop the canvas to achieve the effect of rounded corners.

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        path = new Path();
        path.addCircle(100 + bmpWidth / 2, 100 + bmpHeight / 2, bmpWidth / 2, Path.Direction.CW);
        
        canvas.drawPath(path, paint);

        canvas.save();
        canvas.clipPath(path);
        canvas.drawBitmap(bitmap, 100, 100, paint);
        canvas.restore();
    }

Running below 4.3, the cropping effect cannot be displayed.

This is caused by turning on hardware acceleration.

https://developer.android.com/guide/topics/graphics/hardware-accel.html

Hardware acceleration is enabled by default if your Target API level is >=14, but can also be explicitly enabled.

Hardware acceleration is enabled by default since Android 4.0 (API level 14).

But clipPath is only supported since 18.

So you need to turn off hardware acceleration.

Do not set the attribute android:hardwareAccelerated="false" in the application tag or activity tag of the manifest, this will cause the interface to be unsmooth.

setLayerType(View.LAYER_TYPE_SOFTWARE, null);

 

However, I encountered another problem. On API18, it also displayed abnormal conditions.

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        path = new Path();
        path.addCircle(100 + bmpWidth / 2, 100 + bmpHeight / 2, bmpWidth / 2, Path.Direction.CW);
        
        canvas.drawPath(path, paint);

        canvas.save();
        canvas.clipPath(path);
        canvas.drawBitmap(bitmap, 100, 100, paint);
        canvas.restore();

        canvas.drawBitmap(bitmap, 600, 100, paint);
    }

When the same bitmap is drawn on the canvas, it is abnormal again.

When the third parameter value of addCircle is different, sometimes the display is not normal, and hardware acceleration needs to be turned off.

Not sure if it's an Android bug, or if I'm handling it incorrectly.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325092166&siteId=291194637