Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display text with two-color background?

I need to create an app for android, where the 2-color text will be displayed on the 2-color background. See picture on the left. Then, the line should be moved with animation and result image should be like on the picture on the right.

I have the following questions:

  1. Should I use some 2d engine to do this? Or, will it be OK to use standard views? How to do it?
  2. How to draw the text like on the pictures?

pic1 --------- pic2

like image 661
LA_ Avatar asked Sep 12 '11 18:09

LA_


2 Answers

In Android graphics API i would use clip path to create clip region. Steps:

  • fill canvas with black color:

black canvas

  • draw your white text on canvas:

enter image description here

  • create clip path and apply it to your canvas (see Canvas.clipPath(Path))
  • fill canvas with white color:

enter image description here

  • draw the same text as in step 2 in black on canvas:

enter image description here

like image 88
Ludevik Avatar answered Oct 21 '22 13:10

Ludevik


You can create a custom view that masks your text using a PorterDuff filter.

Here is how it could look:

public class MaskedText extends View {

    String sText;
    Paint p, pReplace, pMask;

    public MaskedText(Context context, AttributeSet attrs) {
        super(context, attrs);

        // base paint for you text
        p = new Paint(Paint.ANTI_ALIAS_FLAG);
        p.setTextSize(40);
        p.setTextAlign(Paint.Align.CENTER);
        p.setColor(0xFF000000);
        p.setStyle(Paint.Style.FILL);

        // replacement color you want for your the part of the text that is masked
        pReplace = new Paint(p);
        pReplace.setColor(0xFFFFFFFF);
        pReplace.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER));

        // color of the drawing you want to mask with text
        pMask = new Paint();
        pMask.setColor(0xFFFF0000);
        pMask.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    }

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

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.save();

        // here you draw the text with the base color. In your case black
        canvas.drawText(sText, getWidth() / 2, getHeight() / 2, p);

        // then draw the shape any graphics that you want on top of it
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, 50, pMask);
        canvas.drawCircle(getWidth() / 2 + 50, getHeight()/2 + 5, 20, pMask);
        canvas.drawCircle(getWidth() / 2 - 45, getHeight()/2 - 10, 30, pMask);

        // finally redraw the text masking the graphics
        canvas.drawText(sText, getWidth()/2, getHeight()/2, pReplace);

        canvas.restore();
    }
}

This is the result: Masked text

like image 28
Pol Avatar answered Oct 21 '22 14:10

Pol