If you know how to do with an image (Bitmap) then you only need a Bitmap that reproduces the TextView.
The following method returns an image (bitmap) representing the contents of the view .
public static Bitmap getViewBitmap(View view){
//Cria um bitmap com as dimensões da view
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(),
Bitmap.Config.ARGB_8888);
//Cria um canvas para escrever no bitmap
Canvas canvas = new Canvas(bitmap);
//Pede à view que escreva o seu conteúdo no bitmap, usando o canvas
//anteriormente criado.
view.draw(canvas);
return bitmap;
}
Note that the method can only be used after the "tree of views" has been created, for example in the onWindowFocusChanged()
method.
Example usage for your case: black letters, white background:
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView textView;
Bitmap textViewBitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text1);
textView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
handleTouch(event.getX(), event.getY());
return true;
}
});
}
private void handleTouch(float x, float y) {
int pixel = textViewBitmap.getPixel((int)x, (int)y);
if(pixel == Color.WHITE){
Toast.makeText(this, "Branco", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Preto", Toast.LENGTH_SHORT).show();
}
}
private static Bitmap getViewBitmap(View view){
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(textViewBitmap == null){
textViewBitmap = getViewBitmap(textView);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app = "http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:textColor="@android:color/black"
android:text="TextView"
android:textSize="40sp"/>
</LinearLayout>