Android TextView与平行四边形背景

时间:2014-08-20 08:24:09

标签: textview android-custom-view android-drawable android-bitmap android-background

我想达到以下效果。即具有平行四边形背景的TextView。

TextView with paralleogram background

我不能使用9补丁,因为背景的颜色是动态的。

理想情况是使用已设置背景的自定义TextView。

有没有实现这个目标?

1 个答案:

答案 0 :(得分:0)

我最终必须创建一个自定义视图,使用绘制路径为左侧和右侧绘制一个三角形。

然后我必须创建另一个扩展线性布局(或相对布局)的自定义视图,并包括左三角视图,文本视图和右三角视图。三角形大小根据视图的高度调整。三角形的填充颜色与textview的背景颜色相匹配。

这一切似乎运作良好,因为我在很多设备上都没有遇到任何问题。它也是列表视图中列表项的一部分,性能似乎很好。

表示三角形:

公共类LabelTriangleView扩展了View {

private boolean mRightSided = false;
private Paint mMainTrianglePaint;
private int mMainTriangleColor;

public LabelTriangleView(Context context) {
    super(context);
    intialise();
}

public LabelTriangleView(Context context, AttributeSet attrs) {
    super(context, attrs);
    intialise();
}

public void setMainColor(int newColor) {
    mMainTriangleColor = newColor;
    invalidate();
    requestLayout();
}

public void setRightSided() {
    mRightSided = true;
    invalidate();
    requestLayout();
}

@Override
protected void onDraw(Canvas canvas) {

    mMainTrianglePaint.setColor(mMainTriangleColor);

    if (mRightSided) {
        canvas.drawPath(getRightSidedPath(), mMainTrianglePaint);
    } else {
        canvas.drawPath(getLeftSidedPath(), mMainTrianglePaint);
    }
}

private void intialise() {
    mMainTrianglePaint = new Paint();
    mMainTrianglePaint.setStyle(Style.FILL);
    mMainTrianglePaint.setAntiAlias(true);
}

private Path getLeftSidedPath() {
    Path path = new Path();
    path.moveTo(this.getMeasuredWidth(), 0);
    path.lineTo(this.getMeasuredWidth(), this.getMeasuredHeight());
    path.lineTo(0, this.getMeasuredHeight());
    path.close();

    return path;
}

private Path getRightSidedPath() {
    Path path = new Path();
    path.moveTo(0, 0);
    path.lineTo(this.getMeasuredWidth(), 0);
    path.lineTo(0, this.getMeasuredHeight());
    path.close();

    return path;
}

}

三角形应足以让任何人开始。我不能在这里发布其余的代码,因为它太复杂而无法删除内容。

但基本上,这就是我所做的:

  1. 创建了一个自定义视图,扩展了一个名为LabelView的RelativeLayout。
  2. 在初始化LabelView时,我添加了一个TextView。
  3. 创建了两个新的自定义LabelTriangleView。一个用于左边,一个用于右边(调用setRightSided)。
  4. 我将LabelTriangleView的高度设置为与TextView相同的高度。
  5. 我将LabelTriangleView的宽度设置为TextView的一半高度。
  6. 然后我将Left LabelTriangleView添加到TextView的左侧。
  7. 我添加了与TextView右侧对齐的右侧LabelTriangleView。
  8. 我使用setMainColor()设置LabelTriangleView的颜色。并为TextView
  9. 的bg使用相同的颜色

    基本上就是这样!