0

Iam new to android.I want to read the text written in a rectangle drawn in canvas.I know that drawText() is used to write the text,is there any way to read the text ? Thanks in advance

4

1 回答 1

1

如果您只是想在矩形内写入文本。最好使用 TextView 而不是 canvas.drawText。

如果你确实想使用 drawText。这是方法。首先,创建 CustomView 类。

public class CustomView extends View{

    String text;
    private Paint paint;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        paint.setColor(Color.BLACK);
    }

    public void setText(String text){
        this.text = text;
        invalidate();
    }

    @Override
    public void onDraw(Canvas canvas){
        canvas.drawText(text, 20, 20, paint);       
        super.onDraw(canvas);
    }

}

在 activitiy_main.xml 中,声明如下。在这种情况下,您绘制了 2 个矩形。请记住为每个矩形设置不同的 id。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.example.apps1.CustomView
        android:id="@+id/custom_view_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <com.example.apps1.CustomView
        android:id="@+id/custom_view_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>    

</LinearLayout>

然后,在 MainActivity 上通过上面给定的 id 找到视图,并将要设置的文本写入矩形。

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String view1Text = "First rectangle";
        String view2Text = "Second rectangle";

        CustomView customView1 = (CustomView)findViewById(R.id.custom_view_1);
        CustomView customView2 = (CustomView)findViewById(R.id.custom_view_2);
        customView1.setText(view1Text);
        customView2.setText(view2Text);

        // get text from customView1 and customView2
        String textOnCustomView1 = customView1.text;
        String textOnCustomView2 = customView2.text;
    }

}

这样,您可以将您写入的文本读取到矩形中。

于 2013-09-06T06:30:44.447 回答