温馨提示×

android radialgradient有哪些实现方式

小樊
81
2024-12-02 09:54:42
栏目: 编程语言

在Android中,RadialGradient(径向渐变)可以通过Canvas API或者使用预定义的GradientDrawable实现。以下是两种实现径向渐变的方法:

  1. 使用Canvas API和Shader(着色器):
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = new View(this);
        view.setDrawingCacheEnabled(true);
        setContentView(view);
    }

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

        // 创建径向渐变
        int centerX = getWidth() / 2;
        int centerY = getHeight() / 2;
        float radius = Math.min(getWidth(), getHeight()) / 4;
        RadialGradient radialGradient = new RadialGradient(centerX, centerY, radius,
                new int[]{0xFF4CAF50, 0xFF8BC34A, 0xFFCDDC39},
                new float[]{0, 0.5f, 1},
                Shader.TileMode.CLAMP);

        // 创建画笔并设置渐变
        Paint paint = new Paint();
        paint.setShader(radialGradient);

        // 绘制渐变矩形
        canvas.drawRect(centerX - radius, centerY - radius, centerX + radius, centerY + radius, paint);
    }
}
  1. 使用预定义的GradientDrawable:
import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = new View(this);
        view.setBackground(createRadialGradient());
        setContentView(view);
    }

    private GradientDrawable createRadialGradient() {
        // 创建径向渐变
        int centerX = getWidth() / 2;
        int centerY = getHeight() / 2;
        float radius = Math.min(getWidth(), getHeight()) / 4;
        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setGradientType(GradientDrawable.RADIAL_GRADIENT);
        gradientDrawable.setCenter(centerX, centerY);
        gradientDrawable.setRadius(radius);
        gradientDrawable.setColor(0xFF4CAF50); // 外圆颜色
        gradientDrawable.setStroke(5, 0xFF8BC34A); // 边框颜色和宽度

        return gradientDrawable;
    }
}

这两种方法都可以实现径向渐变效果。使用Canvas API和Shader提供了更多的自定义选项,而使用预定义的GradientDrawable则更简单快捷。根据你的需求和偏好选择合适的方法。

0