要在Android中绘制ImageView周围的边框,可以使用自定义的Drawable来实现。以下是一个示例代码:
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
public class BorderDrawable extends Drawable {
private int strokeWidth;
private int strokeColor;
private Paint paint;
public BorderDrawable(int strokeWidth, int strokeColor) {
this.strokeWidth = strokeWidth;
this.strokeColor = strokeColor;
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(strokeWidth);
paint.setColor(strokeColor);
}
@Override
public void draw(Canvas canvas) {
Rect bounds = getBounds();
float halfStrokeWidth = strokeWidth / 2f;
float left = bounds.left + halfStrokeWidth;
float top = bounds.top + halfStrokeWidth;
float right = bounds.right - halfStrokeWidth;
float bottom = bounds.bottom - halfStrokeWidth;
canvas.drawRect(left, top, right, bottom, paint);
}
@Override
public void setAlpha(int alpha) {
paint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
paint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return paint.getAlpha();
}
}
ImageView imageView = findViewById(R.id.imageView);
BorderDrawable borderDrawable = new BorderDrawable(5, Color.RED);
imageView.setImageDrawable(borderDrawable);
在这个例子中,我们创建了一个BorderDrawable类来绘制边框。构造函数接受一个边框宽度和边框颜色作为参数。draw()方法在ImageView的边界上绘制一个矩形边框。
然后,在Activity或Fragment中,我们实例化BorderDrawable,并将其设置为ImageView的图像Drawable。
通过调整构造函数中的参数,你可以自定义边框的宽度和颜色。