下面的类使用自定义ShapeDrawable而不是自定义的LayerDrawable实现您想要的功能。 请注意,drawLine
调用中的所有坐标偏移都是为了防止重叠,并确保我们可以看到周边线条的整个宽度。
public class MyShapeDrawable extends ShapeDrawable {
private int startX, startY, endX, endY;
private float mLineWidth = 1f;
private Paint mLinePaint;
public MyShapeDrawable() {
// No color specified, so call constructor with default color White
this(Color.WHITE);
}
public MyShapeDrawable(int color) {
// use the setter defined below, to set the main color for this drawable
setColor(color);
// setup the Paint for drawing the lines
mLinePaint = new Paint();
mLinePaint.setStyle(Paint.Style.STROKE);
mLinePaint.setStrokeWidth(mLineWidth);
}
public void setColor(int color) {
Paint paint = getPaint();
paint.setColor(color);
}
public void setLineWidth(float lineWidth) {
mLineWidth = lineWidth;
mLinePaint.setStrokeWidth(mLineWidth);
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
// bottom black line
////////////////////
mLinePaint.setColor(Color.BLACK);
mLinePaint.setAlpha((int) (255 * 0.9)); // Opacity 90%
canvas.drawLine(
getBounds().left, getBounds().bottom - mLineWidth * 0.5f,
getBounds().right, getBounds().bottom - mLineWidth * 0.5f,
mLinePaint);
// translucent grey rim
///////////////////////
mLinePaint.setColor(Color.parseColor("#888888"));
mLinePaint.setAlpha((int) (255 * 0.7)); // Opacity 70%
// top
canvas.drawLine(
getBounds().left, getBounds().top + mLineWidth * 0.5f,
getBounds().right, getBounds().top + mLineWidth * 0.5f,
mLinePaint);
// left
canvas.drawLine(
getBounds().left + mLineWidth * 0.5f, getBounds().bottom - mLineWidth,
getBounds().left + mLineWidth * 0.5f, getBounds().top + mLineWidth,
mLinePaint);
// right
canvas.drawLine(
getBounds().right - mLineWidth * 0.5f, getBounds().bottom - mLineWidth,
getBounds().right - mLineWidth * 0.5f, getBounds().top + mLineWidth,
mLinePaint);
// top white line
/////////////////
mLinePaint.setColor(Color.WHITE);
mLinePaint.setAlpha((int) (255 * 0.5)); // Opacity 50%
canvas.drawLine(
getBounds().left + mLineWidth, getBounds().top + mLineWidth * 1.5f,
getBounds().right - mLineWidth, getBounds().top + mLineWidth * 1.5f,
mLinePaint);
}
如下你可以使用这个类:
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
MyShapeDrawable myShapeDrawable = new MyShapeDrawable(getResources().getColor(R.color.yellow));
FrameLayout frameLayout = (FrameLayout) findViewById(R.id.test);
frameLayout.setBackgroundDrawable(myShapeDrawable);
}
}
你的具体问题是什么?要创建'LayerDrawable',请使用构造函数。 – CommonsWare 2014-10-02 21:25:15
@CommonsWare我的具体问题是如何使用分层绘制来创建这个。 – jcaruso 2014-10-02 21:26:06