Android for Scratch effect

Source: Internet
Author: User
Tags gety transparent color

Just a few months ago, when I was in touch with Android, I did a little project, which also used a scratch-like effect, and now put the code out.

First, do something like an eraser, and then erase the handwriting on the paper.

/** * FileName:SplashActivity.java * * @desc eraser function, similar to scratch effect * @author HTP * @Date 20140311 * @version 1.00 */public class Text_rubbler extends TextView {private float touch_tolerance;//fill the distance, make the line more natural, softer, the smaller the value, the softer. Private final int bgcolor;//bitmap private Bitmap mbitmap;//canvas private canvas mcanvas;//brush private Paint mpaint;private Pat  H mpath;private Float MX, my;private boolean isdraw = False;public Text_rubbler (context context) {/** * @param context context */super (context);} Public Text_rubbler (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, defstyle);//BgColor =//att Rs.getattributeintvalue ("http://schemas.android.com/apk/res/android",//"TextColor", 0xFFFFFF);// System.out.println ("Color:" +bgcolor);} Public Text_rubbler (context context, AttributeSet Attrs) {Super (context, attrs);//BgColor =// Attrs.getattributeintvalue ("http://schemas.android.com/apk/res/android",//"TextColor", 0xFFFFFF);// System.out.println (BgColor);//System.out.println (Attrs.getattributevaluE ("http://schemas.android.com/apk/res/android",//"Layout_width");} @Overrideprotected void OnDraw (canvas canvas) {Super.ondraw (canvas), if (Isdraw) {Mcanvas.drawpath (MPath, mpaint);// Mcanvas.drawpoint (MX, MY, Mpaint); Canvas.drawbitmap (mbitmap, 0, 0, null);}} /** * Turn on erase function * * @param bgColor * Cover background color * @param paintstrokewidth * Contact (RUBBER) Width * @param touchtolera NCE * Fills the distance, the lower the value, the softer. */public void Beginrubbler (final int bgColor, final int paintstrokewidth,float touchtolerance) {touch_tolerance = Touchto lerance;//Set Brush mpaint = new Paint ();//Mpaint.setalpha (0);//brush across the traces will become transparent color mpaint.setcolor (color.black); This cannot be a transparent color mpaint.setxfermode (new Porterduffxfermode (PorterDuff.Mode.DST_OUT));//or//Mpaint.setalpha (0);// Mpaint.setxfermode (New Porterduffxfermode (PorterDuff.Mode.DST_IN)); Mpaint.setantialias (true); Mpaint.setdither ( true); Mpaint.setstyle (Paint.Style.STROKE); Mpaint.setstrokejoin (Paint.Join.ROUND); Front fillet mpaint.setstrokecap (Paint.Cap.ROUND); Rear Fillet mpaint.setsTrokewidth (Paintstrokewidth); Pen width//Trace MPath = new Path ();; /overwrite//if (Getlayoutparams (). width = = layoutparams.fill_parent) {////}mbitmap = Bitmap.createbitmap (Getlayoutparams (). Width,getlayoutparams (). Height, config.argb_8888) Mcanvas = new Canvas (MBITMAP); Mcanvas.drawcolor (bgColor); Isdraw = true;} @Overridepublic boolean ontouchevent (Motionevent event) {if (!isdraw) {return true;} Switch (event.getaction ()) {case Motionevent.action_down://Contact Press//TouchDown (EVENT.GETRAWX (), Event.getrawy ()); TouchDown (Event.getx (), event.gety ()); invalidate (); Break;case motionevent.action_move://Contact Move touchmove (event.getx (), event.gety ()); invalidate (); Break;case motionevent.action_up://Contacts Bounce Touchup (Event.getx (), event.gety ()); Invalidate (); break;default:break;} return true;} private void TouchDown (float x, float y) {mpath.reset (); Mpath.moveto (x, y); MX = X;my = y;} private void TouchMove (float x, float y) {float dx = math.abs (x-mx); float dy = Math.Abs (y-my); if (DX >= touch_toler ance | | Dy >= TOUCH_tolerance) {mpath.quadto (MX, my, (x + MX)/2, (y + MY)/2), mx = X;my = y;}} private void TouchUp (float x, float y) {mpath.lineto (x, y); Mcanvas.drawpath (MPath, Mpaint); Mpath.reset ();}}

The next step is to erase with Eraser

/** * FileName:RubblerAct.java * @Desc This class will show a scratch area on the activity by calling Text_rubbler, can start touch event * @author HTP * @Date 2014  0312 * @version 1.00 */public class Rubbleract extends Activity {//After scraping the text shows private TextView tv_rubbler;//get scraped content private Sentence msentence;//next private TextView tv_next; @Overridepublic void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate);//Setcontentview (new rubble (this, "Thank you", New Rect (200,//300,250), 2,1f,14)) ;///////////////////////////////////////////setcontentview (R.layout.rubbler);//The color set must be transparent. ((Text_rubbler) Findviewbyid (R.id.rubbler)). Beginrubbler (0xFFFFFFFF, 20,1f);//Set the width of the eraser, etc. msentence = new sentence (); /random Initialization text Tv_rubbler = (TextView) Findviewbyid (R.id.rubbler); String str = msentence.getsentence (); Tv_rubbler.settext (str); tv_next = (TextView) Findviewbyid (r.id.tv_next);// Click Next Tv_next.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated Method stubstring str = msentence.Getsentence (); Tv_rubbler.settext (str);((Text_rubbler) Findviewbyid (R.id.rubbler))//Initialize state. Beginrubbler ( 0xFFFFFFFF, 1f);});} Class Rubble extends View {private final int paint_stroke_width;private final float touch_tolerance;//fill the distance to make the line more natural, softer, less value , the more gentle. Private final int text_size;private Bitmap mbitmap;//canvas private canvas mcanvas;//brush private Paint mpaint;private Path Mpat h;private float MX, my;private final int X, Y, W, h;private final Rect touchrect;public Rubble (context context, String BgT Ext, Rect rect,int paintstrokewidth, float touchtolerance, int textSize) {super (context); setfocusable (true); Touchrect = Rect W = Rect.right-rect.left; H = Rect.bottom-rect.top; X = Rect.left; Y = Rect.top; Text_size = textSize; Paint_stroke_width = Paintstrokewidth; Touch_tolerance = Touchtolerance;setbackground (Touchrect, Bgtext); Initdrowtools ();} private void SetBackground (rect rect, String bgtext) {displaymetrics dm = new Displaymetrics ();d m = this.getresources (). GE Tdisplaymetrics (); Bitmap Bitmap = Bitmap.createbitmap (Dm.widthpixels,dm.heightpixels, config.argb_8888); Canvas canvas = new canvas (bitmap); Paint paint = new paint ();p aint.setcolor (0x88000000);//Paint.setstyle (Style.stroke);//Paint.settextalign ( Align.center);p aint.settextsize (text_size);//Paint.settextscalex (1.5f); Canvas.drawcolor (color.white);// Stooped coordinates are not well controlled int x = rect.left+ (Rect.right-rect.left-bgtext.length () * text_size)/2;int y = rect.top + (rect.bottom-re ct.top-text_size)/2;//int y = 218+25;canvas.drawtext (Bgtext, x, y, paint);D rawable drawable = new Bitmapdrawable (bitm AP); setbackgrounddrawable (drawable);} private void Initdrowtools () {//set brush Mpaint = new Paint ();//Mpaint.setalpha (0);//brush across the traces will become transparent color mpaint.setcolor ( Color.Black); This cannot be a transparent color mpaint.setxfermode (new Porterduffxfermode (PorterDuff.Mode.DST_OUT));//or//Mpaint.setalpha (0);// Mpaint.setxfermode (new//porterduffxfermode (PorterDuff.Mode.DST_IN)); Mpaint.setantialias (true); Mpaint.setdither (true); Mpaint.setstyle (Paint.Style.STROKE); mpaint.seTstrokejoin (Paint.Join.ROUND); Front fillet mpaint.setstrokecap (Paint.Cap.ROUND); Posterior fillet mpaint.setstrokewidth (paint_stroke_width); Pen width//Trace MPath = new Path ();; /Overwrite Mbitmap = Bitmap.createbitmap (W, H, config.argb_8888); Mcanvas = new Canvas (MBITMAP); Mcanvas.drawcolor (0x88000000);} @Overrideprotected void OnDraw (canvas canvas) {super.ondraw (canvas); Mcanvas.drawpath (MPath, mpaint);// Mcanvas.drawpoint (MX, MY, Mpaint); Canvas.drawbitmap (Mbitmap, X, Y, null);} @Overridepublic boolean ontouchevent (Motionevent event) {System.out.print ("x--" + event.getx ()); System.out.println ("y--" + event.gety ()), if (!touchrect.contains (int) event.getx (), (int) event.gety ())) {return false;} Switch (event.getaction ()) {//Contacts press case Motionevent.action_down: {TouchDown (EVENT.GETRAWX (), Event.getrawy ()); TouchDown (Event.getx ()-Touchrect.left, Event.gety ()-touchrect.top); invalidate (); break;} Case Motionevent.action_move://Contact Move touchmove (Event.getx ()-Touchrect.left, Event.gety ()-touchrect.top); invalidate (); Break;case MOTIONEVENT.ACTION_UP://Contacts Bounce Up Touchup (Event.getx ()-Touchrect.left, Event.gety ()-touchrect.top); invalidate (); break; Default:break;} return true;} private void TouchDown (float x, float y) {mpath.reset (); Mpath.moveto (x, y); MX = X;my = y;} private void TouchMove (float x, float y) {float dx = math.abs (x-mx); float dy = Math.Abs (y-my); if (DX >= touch_toler ance | | Dy >= touch_tolerance) {mpath.quadto (MX, my, (x + MX)/2, (y + MY)/2), mx = X;my = y;}} private void TouchUp (float x, float y) {mpath.lineto (x, y); Mcanvas.drawpath (MPath, Mpaint); Mpath.reset ();}} /** * Keyboard event, when the back button is pressed to ask whether to press the exit program again *///exit time private long exittime = 0; @Overridepublic boolean onKeyDown (int keycode, Keyev Ent event) {if (keycode = = keyevent.keycode_back&& event.getaction () = = Keyevent.action_down) {if ( System.currenttimemillis ()-Exittime) > {toast.maketext (Getapplicationcontext (), "Press again to exit the program", Toast.length_ Short). Show (); exittime = System.currenttimemillis ();} else {finish (); System.exit (0);} Returntrue;} Return Super.onkeydown (KeyCode, event);}}

The implementation results are as follows:


Android for Scratch effect

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.