我想在圖像周圍繪製邊框。但我無法在ImageView自身對齊邊框(就像它主要完成的那樣),因爲我用ImageMatrix翻譯和縮放ImageView內部的圖像(ImageView本身是fill_parent /填充整個屏幕)。我有想法添加第二個圖像(看起來像一個邊框),並翻譯&縮放,它應該像應該有一個邊框的圖像相同的方式,但這樣做並不是很方便。 有沒有人有更好的主意來實現這一目標?安卓在ImageView中繪製邊框
謝謝!
我想在圖像周圍繪製邊框。但我無法在ImageView自身對齊邊框(就像它主要完成的那樣),因爲我用ImageMatrix翻譯和縮放ImageView內部的圖像(ImageView本身是fill_parent /填充整個屏幕)。我有想法添加第二個圖像(看起來像一個邊框),並翻譯&縮放,它應該像應該有一個邊框的圖像相同的方式,但這樣做並不是很方便。 有沒有人有更好的主意來實現這一目標?安卓在ImageView中繪製邊框
謝謝!
有兩種方法可以實現這一點: 1)爲圖像添加填充併爲其設置背景顏色。
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)另一種選擇是覆蓋您的視圖的繪製方法有繪製邊框:
@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%肯定它是正確的,但這些是方式:)正切邊界應該是你的視圖的邊界矩形 - (0,0,width,height )。
或者,把ImageView的在某種佈局和剛剛成立的填充:
static class BorderView extends FrameLayout
{
public ImageView imageView;
public BorderView(Context context)
{
super(context);
setLayoutParams(//wrap content)
imageView = new ImageView(context);//set image and so forth
addView(imageView);
}
public void addSelectionBorder()
{
int border = 8;
setPadding(border,border,border,border);
setBackgroundColor(Color.BLUE);
}
public void removeSelectionBorder()
{
int border = 0;
setPadding(border,border,border,border);
setBackgroundColor(Color.BLACK);
}
}
我用第二個選項。當我拖動圖像時,其邊框停留在其座標處。我添加了一個CustomView.setBorder方法,其邊界更新(與ImageMatrix更新並行),但不起作用。我是否需要調用draw-method或什麼? 啊。似乎它做錯了什麼。現在它的工作。 – andineupert