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:
- Should I use some 2d engine to do this? Or, will it be OK to use standard views? How to do it?
- How to draw开发者_JAVA技巧 the text like on the pictures?
In Android graphics API i would use clip path to create clip region. Steps:
- fill canvas with black color:
- draw your white text on canvas:
- create clip path and apply it to your canvas (see Canvas.clipPath(Path))
- fill canvas with white color:
- draw the same text as in step 2 in black on canvas:
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
This is not complete answer I just giving suggestions. I know one possible solution how can you do the picture on the left and the picture on the right. But The part I cant figured out is the animation. I mean if you want smooth animation between states. If you just want to swap views that is easy, just take a view fliper and that it, but I do not think that you want to achieve that...
One of the things you can do is to set background let say with 320 width and let say 0-160 white and 160-320 black. Then
tv.setText(Html.fromHtml("<font color='black'>black on white</font> <font color='white'>white on black</font>"));
of course you will need to do precise calculation of how many letters will be black and how many white, but that is the concept
精彩评论