在Android中,自定义ProgressDrawable的形状可以通过创建一个新的类并继承自ProgressDrawable来实现。以下是一个简单的示例,展示了如何创建一个带有自定义形状的ProgressDrawable:
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
public class CustomProgressDrawable extends Drawable {
private Paint paint;
public CustomProgressDrawable() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
}
@Override
public void draw(Canvas canvas) {
// 在这里绘制你的自定义形状
Rect bounds = getBounds();
int centerX = bounds.centerX();
int centerY = bounds.centerY();
int radius = Math.min(centerX, centerY) - (int) paint.getStrokeWidth() / 2;
paint.setColor(0xFF009688);
canvas.drawCircle(centerX, centerY, radius, paint);
paint.setColor(0xFFFF5722);
canvas.drawArc(bounds.left, bounds.top, bounds.right, bounds.bottom, 270, 120, false, 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;
}
}
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="100"
android:progress="50" />
ProgressBar progressBar = findViewById(R.id.progressBar);
CustomProgressDrawable customProgressDrawable = new CustomProgressDrawable();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
progressBar.setProgressDrawable(customProgressDrawable);
} else {
progressBar.setIndeterminateDrawable(customProgressDrawable);
}
这样,你就可以看到一个带有自定义形状的ProgressBar了。你可以根据需要修改CustomProgressDrawable
类中的draw()
方法,以绘制你想要的形状。