要制作自定义的可绘制形状,可以通过创建自定义的Drawable类来实现。以下是一个简单的示例,演示如何制作一个带有圆角的矩形形状:
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
public class RoundRectDrawable extends Drawable {
private Paint paint;
private int color;
private float cornerRadius;
public RoundRectDrawable(int color, float cornerRadius) {
this.color = color;
this.cornerRadius = cornerRadius;
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
}
@Override
public void draw(Canvas canvas) {
RectF rectF = new RectF(getBounds());
canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, paint);
}
@Override
public void setAlpha(int alpha) {
paint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
paint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RoundRectDrawable roundRectDrawable = new RoundRectDrawable(Color.BLUE, 20f);
View view = findViewById(R.id.my_view);
view.setBackground(roundRectDrawable);
}
}
在这个示例中,RoundRectDrawable类继承自Drawable类,并重写了draw()方法来绘制一个圆角矩形形状。您可以在构造函数中指定矩形的颜色和圆角半径,然后通过setBounds()方法来设置形状的边界。最后,您可以将RoundRectDrawable对象设置为视图的背景,以显示该自定义形状。
请注意,上述示例只是一个简单的示例,用于演示如何制作自定义形状。您可以根据自己的需求进一步自定义和优化该Drawable类。