[Android] Realize radar scanning effect, use custom View to draw radar scanning animation

To implement the radar scanning effect on Android, you can use a custom View to draw the radar scanning animation. Here is a simple sample code:

  1. Create a custom View class named RadarView, inheriting from View:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class RadarView extends View {
    
    

    private Paint paint;
    private float radius;

    public RadarView(Context context, AttributeSet attrs) {
    
    
        super(context, attrs);
        paint = new Paint();
        paint.setColor(Color.BLUE);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(3);
        radius = 0;
    }

    @Override
    protected void onDraw(Canvas canvas) {
    
    
        super.onDraw(canvas);
        int centerX = getWidth() / 2;
        int centerY = getHeight() / 2;
        canvas.drawCircle(centerX, centerY, radius, paint);
        radius += 5;
        if (radius > Math.min(centerX, centerY)) {
    
    
            radius = 0;
        }
        invalidate();
    }
}

In the above code, we created a RadarView class, inherited from View, and initialized the brush and radius in the constructor.

In the onDraw method, we first get the center coordinates of the View, and then use a brush to draw a circle, the center of which is the center coordinates of the View, and the radius is radius.

Next, we increase the value of radius each time we call onDraw to gradually increase the radius of the circle, and trigger the redrawing of the View through the invalidate() method.

Finally, when the radius exceeds half of the View's width and height, we reset the radius to 0 to achieve a circular radar scanning effect.

  1. Add RadarView in the layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <com.example.myapplication.RadarView
        android:layout_width="200dp"
        android:layout_height="200dp" />

</LinearLayout>

In this example, we add the RadarView to a LinearLayout and set the width and height to 200dp.

Now, run your application and you will see an animation of a radar scan.

This is just a simple sample code, you can customize and expand according to your needs, such as adding scan lines, dynamically changing colors, etc.

Guess you like

Origin blog.csdn.net/gao511147456/article/details/131426021