android textured text

后端 未结 3 2095
说谎
说谎 2021-01-06 03:08

How can I make a text with texture instead of text color or gradient(for example png file)? Something like this. I understand the logic, that I should make text color transp

3条回答
  •  耶瑟儿~
    2021-01-06 03:59

    Here's a way of doing it using PorterDuffXfermode.

    public class MainActivity extends Activity {
        private EditText mEditText;
        private ImageView mImageView;
        private Bitmap mTexture;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mEditText = (EditText) findViewById(R.id.activity_main_edittext);
            mImageView = (ImageView) findViewById(R.id.activity_main_image);
    
            mTexture = BitmapFactory.decodeResource(getResources(),
                    R.drawable.texture);
        }
    
        public void onTextCreate(View v) {
            final String text = mEditText.getEditableText().toString();
    
            Bitmap result = Bitmap.createBitmap(mTexture.getWidth(),
                    mTexture.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setTextSize(200);
            paint.setARGB(255, 0, 0, 0);
    
            canvas.drawText(text, 200, 200, paint);
            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(mTexture, 0, 0, paint);
            paint.setXfermode(null);
    
            mImageView.setImageBitmap(result);
        }
    }
    

    The layout is pretty simple:

    
    
        
    
        
    
        

    This code with write text using canvas.drawText(). If you want to use a regular TextView, you can:

    • create the TextView
    • Set the text
    • drawing the TextView into a canvas using textView.draw(canvas);
    • Instead of doing canvas.drawText() use canvas.drawBitmap()

提交回复
热议问题