Android: Overlay text in picture, support drag to change position

Source: Internet
Author: User
Tags float max gety

The reason why this is a demo, is because of the recent project has a wonderful demand: users take photos, share to the same time to add notes, want to get the user in the pop-up box input content. Saved on your own server. In fact, this content program is not available, so took a compromise, the text directly written on the picture.

First, the demo:


Function:

1. The user freely input content, can be manually wrapped, and the line full will also take the initiative to change lines.

2. Drag to change the position of the text in the picture (the text will not exceed the image area).

3. After clicking the "Generate Picture" button, create a picture file with text.

The code is not much, directly all pasted up:

Activity:

/** * Write text in the picture (mode), support drag text.

<br/> * Description: Very obviously, the way will reduce the quality of the picture. Suppose you need to keep the picture quality in the way you use canvas. Draw text directly above the picture (just use this way to make the text drag more complex). */public class Mainactivity extends Appcompatactivity {//Picture component private ImageView ImageView; The text component in the picture is private TextView tvinimage; The parent component of the picture and text private View Containerview; Parent component Size Private float imagewidth, ImageHeight, Imagepositionx, Imagepositiony; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.image_with_text); ImageView = (ImageView) Findviewbyid (r.id.writetext_img); EditText EditText = (EditText) Findviewbyid (R.id.writetext_et); Tvinimage = (TextView) Findviewbyid (R.ID.WRITETEXT_IMAGE_TV); Containerview = Findviewbyid (R.ID.WRITETEXT_IMG_RL); Imageview.getviewtreeobserver (). Addongloballayoutlistener (New Viewtreeobserver.ongloballayoutlistener () {@Over Ride public void Ongloballayout () {Imageview.getvIewtreeobserver (). Removeongloballayoutlistener (this); Imagepositionx = Imageview.getx (); Imagepositiony = Imageview.gety (); ImageWidth = Imageview.getwidth (); ImageHeight = Imageview.getheight (); Sets the text size tvinimage.setmaxwidth ((int) imagewidth); } }); Imageview.setimagebitmap (Getscaledbitmap (r.mipmap.test_img)); Input box Edittext.addtextchangedlistener (new Textwatcher () {@Override public void Beforetextcha Nged (charsequence s, int start, int count, int after) {} @Override public void Ontextcha Nged (charsequence s, int start, int before, int count) {if (s.tostring (). Equals ("")) { Tvinimage.setvisibility (view.invisible); } else {tvinimage.setvisibility (view.visible); Tvinimage.settext (s); } } @Override public void aftertextchanged (Editable s) {}}); Final Gesturedetector gesturedetector = new Gesturedetector (This, new Simplegesturelistenerimpl ()); Move tvinimage.setontouchlistener (New View.ontouchlistener () {@Override public boolean Ontou CH (View V, motionevent event) {gesturedetector.ontouchevent (event); return true; } }); }//Confirm, generate picture public void confirm (view view) {Bitmap BM = Loadbitmapfromview (Containerview); String FilePath = environment.getexternalstoragedirectory () + File.separator + "image_with_text.jpg"; try {bm.compress (Bitmap.CompressFormat.JPEG, +, new FileOutputStream (FilePath)); Toast.maketext (This, "Picture saved to: SD card root Folder/image_with_text.jpg", Toast.length_long). Show (); } catch (FileNotFoundException e) {e.printstacktrace (); }//To get the contents of the view display as a picture (similar to) public static Bitmap Loadbitmapfromview (view view) {Bitmap Bitmap = Bitmap.createbitmap (View.getwidth (), view.ge Theight (), Bitmap.Config.ARGB_8888); Canvas canvas = new canvas (bitmap); View.draw (canvas); return bitmap; } private int count = 0; Tvinimage x-direction and y-direction move amount private float mDx, mDy; Move Private class Simplegesturelistenerimpl extends Gesturedetector.simpleongesturelistener {@Override public boolean onscroll (Motionevent E1, motionevent E2, float Distancex, float distancey) {///move right, Distancex is negative 。 When you move to the left. The Distancey is negative when the Distancex is moving forward//down. When you move up. Distancey is a positive count++; MDx-= Distancex; MDy-= Distancey; Bounds checking mDx = Calposition (Imagepositionx-tvinimage.getx (), Imagepositionx + ImageWidth-(Tvinimage.getx () + t Vinimage.getwidth ()), mDx); MDy = Calposition (Imagepositiony-tvinimage.gety (), Imagepositiony + ImageHeight-(tvinimage.gety () + Tvinimage.getheight ()), mDy); Control Refresh frequency if (count% 5 = = 0) {tvinimage.setx (Tvinimage.getx () + mDx); Tvinimage.sety (tvinimage.gety () + mDy); } return true; }}//Calculate the correct display position (cannot exceed the boundary) private float calposition (float min, float max, float current) {if (Current < min) {return min; } if (current > Max) {return max; } return current; }//Get compressed Bitmap private Bitmap getscaledbitmap (int resId) {bitmapfactory.options opt = new Bitmapfactory.op tions (); Opt.injustdecodebounds = true; Bitmapfactory.decoderesource (Getresources (), resId, opt); Opt.insamplesize = Utility.calculateinsamplesize (OPT, 600, 800); Opt.injustdecodebounds = false; Return Bitmapfactory.decoderesource (Getresources (), resId, opt); }}

A tool class:

public class Utility {    //calculates insamplesize value. Compress picture public    static int calculateinsamplesize (bitmapfactory.options Options, int reqwidth, int reqheight) {        // Raw height and width of image        final int height = options.outheight;        Final int width = options.outwidth;        int insamplesize = 1;        if (Height > Reqheight | | width > reqwidth) {            final int halfheight = HEIGHT/2;            Final int halfwidth = WIDTH/2;            Calculate the largest insamplesize value is a power of 2 and keeps both            //height and width larger than the R equested height and width.            while ((halfheight/insamplesize) > Reqheight && (halfwidth/insamplesize) > Reqwidth) {                insamplesize *= 2;            }        }        return insamplesize;}    }
Layout file:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/    Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " android:padding= "10DP" > <relativelayout android:id= "@+id/writetext_img_rl" android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "Center_horizontal" > &L T;imageview android:id= "@+id/writetext_img" android:layout_width= "Wrap_content" android:l ayout_height= "Wrap_content" android:maxheight= "360DP" android:adjustviewbounds= "true" and roid:contentdescription= "@null"/> <textview android:id= "@+id/writetext_image_tv" Androi            D:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:visibility= "Invisible" Android:layout_centerinparEnt= "true" android:background= "#79652a" android:clickable= "true" android:padding= "4DP" Android:textcolor= "@android: Color/white" android:textsize= "15sp"/> </RelativeLayout> & Lt EditText android:id= "@+id/writetext_et" android:layout_width= "match_parent" android:layout_height= "WR Ap_content "android:layout_margintop=" 8DP "android:hint=" add comment "/> <button android:layout_wid Th= "Wrap_content" android:layout_height= "Wrap_content" android:onclick= "confirm" android:text= "Generate picture" /></linearlayout>
< finish >




Android: Overlay text in picture, support drag to change position

Related Article

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.