如何在Android中为textview提供弯曲的形状

时间:2016-01-11 09:07:58

标签: android android-studio

大家好,我是Android的新手。我想在上传图片时设计一个textview。这有可能像textview一样塑造吗?如果有可能请帮助我。在此先感谢。enter image description here

3 个答案:

答案 0 :(得分:1)

[ss[1] 我创建了有关本文的简单自定义视图。您将使用setText(String arg)方法而不是setText(CharSquence文本)。

public class CurvedTextView extends TextView {

    private Context mContext;
    private int width, height;
    private Paint textPaint, drawPaint;
    private Path mPath;
    private String mText = null;


    public CurvedTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public CurvedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CurvedTextView(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context){
        mContext = context;
        width = height = -1;
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextSize(18.0f);
        textPaint.setColor(Color.WHITE);
        drawPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        drawPaint.setColor(Color.RED);
        drawPaint.setStrokeCap(Paint.Cap.ROUND);

        getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {

            @Override
            public boolean onPreDraw() {
                getViewTreeObserver().removeOnPreDrawListener(this);
                width = getWidth();
                height = getHeight();
                mPath = new Path();
                mPath.moveTo(getLeft(), getTop());
                mPath.lineTo(getLeft(), getTop());
                mPath.quadTo(height / 2, height / 2, getLeft(), height);
                mPath.lineTo(width, height);
                mPath.lineTo(width, 0);
                mPath.lineTo(0, 0);
                mPath.close();
                return false;
            }
        });
    }

    public void setText(String text){
        mText = text;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(mPath, drawPaint);
        if(mText != null){
            canvas.drawText(mText, height/2, height/2, textPaint);
        }
    }

}

答案 1 :(得分:0)

您可以使用自定义背景图片。在drawable文件夹中创建custom_image.xml,在mainActivity.xml中使用它作为背景参数。像这样:

机器人:背景= “@绘制/ custom_image”

答案 2 :(得分:0)

步骤1:将其保存在drawable文件夹中作为curved_view.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >         
   <stroke
          android:width="1dp"
          android:color="@color/common_border_color" />

   <solid android:color="#ffffff" />

   <padding
           android:left="1dp"
           android:right="1dp"
           android:top="1dp" />

   <corners android:radius="4dp" />
</shape>

步骤2:

设置文本视图的背景属性,如下所示

android:background="@drawable/curved_view"