gpt4 book ai didi

Android在ImageView中绘制边框

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:23:55 25 4
gpt4 key购买 nike

我想在图像周围画一个边框。但是我无法在 ImageView 本身对齐边框(就像它大部分完成的那样),因为我使用 ImageMatrix 平移和缩放 ImageView 内部的图像(ImageView 本身是 fill_parent/填充整个屏幕)。我有想法添加第二个图像(看起来像边框)并以与应该有边框的图像相同的方式转换和缩放它,但这样做不是很方便。有没有人有更好的想法来实现该目标?

最佳答案

有两种方法可以实现:1) 向 imageView 添加填充并为其设置背景颜色。

final ImageView imageView = new ImageView(context);
imageView.setPadding(2*border,2*border,0,0);
final ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(width,height);
params.leftMargin = marginYouWouldSet + border;
params.topMargin = marginYouWouldSet + border;
imageView.setBackgroundDrawable(drawable);
imageView.setBackgroundColor(borderColor);
addView(imageView, params);

2) 另一种选择是重写 View 的绘制方法并在那里绘制边框:

@Override
protected void dispatchDraw(Canvas canvas)
{
borderDrawable.draw(canvas);
super.dispatchDraw(canvas);
}
...
public class BorderDrawable extends Drawable{

private Rect mBounds;
private Paint mBorderPaint;

public BorderDrawable(Rect bounds, int thickness, int color) {
mBounds = bounds;
mBorderPaint = new Paint();
mBorderPaint.setStrokeWidth(thickness);
mBorderPaint.setColor(color);
}

@Override
public void draw(Canvas canvas) {
//left border
canvas.drawLine(
mBounds.left - thickness/2,
mBounds.top,
mBounds.left - thickness/2,
mBounds.bottom,
mBorderPaint);
//top border
canvas.drawLine(
mBounds.left,
mBounds.top - thickness/2,
mBounds.right,
mBounds.top - thickness/2,
mBorderPaint);
//right border
canvas.drawLine(
mBounds.right + thickness/2,
mBounds.top,
mBounds.right + thickness/2,
mBounds.bottom,
mBorderPaint);
//bottom border
canvas.drawLine(
mBounds.left,
mBounds.bottom + thickness/2,
mBounds.right,
mBounds.bottom + thickness/2,
mBorderPaint);
}

}

请注意,您要给出要绘制的线的中间部分(!)而且我还没有运行,也没有编译它,所以我不能 100% 确定它是正确的,但这些是方法: ) 矩形边界应该是您 View 的边界矩形 - (0,0,width,height)。

关于Android在ImageView中绘制边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7626554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com