Android: overlay text in an image. You can drag it to change the position,

Source: Internet
Author: User
Tags float max gety

Android: overlay text in an image. You can drag it to change the position,

This Demo has been made because there is a strange demand in the recent project: After a user takes a photo and adds remarks when sharing it, he wants to get the content entered in the pop-up box of the user, save it to your server. In fact, this content program cannot be obtained, so a compromise was adopted to write the text directly on the image.

First, go to the Demo:


Function:

1. You can enter the content freely. You can manually wrap the text, and the text will be automatically wrapped when the line is full.

2. You can drag to change the text position in the image (the text does not exceed the image area ).

3. Click "generate image" to generate an image file with text.

There are not many codes, and all of them are directly attached:

Activity:

/*** Write the text in an image (mode). You can drag the text. <Br/> * Note: Obviously, the image quality is reduced. To maintain the image quality, you can use the canvas method to draw the text directly on the image (however, it is more complicated to use this method to drag the text ). */Public class MainActivity extends AppCompatActivity {// image component private ImageView imageView; // The Text Component private TextView tvInImage in the image; // The parent component private View containerView of the image and text; // size of the parent component 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 () {@ Override public void onGlobalLayout () {imageView. getViewTreeObserver (). removeOnGlobalLayoutListener (this); imagePositionX = imageView. getX (); imagePositionY = imageView. getY (); imageWidth = imageView. getWidth (); imageHeight = imageView. getHeight (); // set the text size tvInImage. setMaxWidth (int) imageWidth) ;}}); imageView. setImageBitmap (getScaledBitmap (R. mipmap. test_img); // input box editText. addTextChangedListener (new TextWatcher () {@ Override public void beforeTextChanged (CharSequence s, int start, int count, int after) {}@ Override public void onTextChanged (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 onTouch (View v, MotionEvent event) {gestureDetector. onTouchEvent (event); return true ;}}) ;}// confirm and generate the image 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, 100, new FileOutputStream (filePath); Toast. makeText (this, "the image has been saved to: SD card root directory/image_with_text.jpg", Toast. LENGTH_LONG ). show ();} catch (FileNotFoundException e) {e. printStackTrace () ;}}// obtain the content displayed by the View in the form of an image (similar to) public static Bitmap loadBitmapFromView (View view) {Bitmap bitmap = Bitmap. createBitmap (view. getWidth (), view. getHeight (), Bitmap. config. ARGB_8888); Canvas canvas = new Canvas (bitmap); view. draw (canvas); return bitmap;} private int count = 0; // The number of rows in the x and y directions of tvInImage: private float mDx and mDy; // The number of rows in the private class SimpleGestureListenerImpl extends GestureDetector. simpleOnGestureListener {@ Override public boolean onScroll (MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {// when moving to the right, distanceX is negative; when moving to the left, distanceX is positive // when it moves down, distanceY is negative; when it moves up, distanceY is positive count ++; mDx-= distanceX; mDy-= distanceY; // border check mDx = calPosition (imagePositionX-tvInImage. getX (), imagePositionX + imageWidth-(tvInImage. getX () + tvInImage. getWidth (), mDx); mDy = calPosition (imagePositionY-tvInImage. getY (), imagePositionY + imageHeight-(tvInImage. getY () + tvInImage. getHeight (), mDy); // controls the 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 ;} // obtain the compressed bitmap private Bitmap getScaledBitmap (int resId) {BitmapFactory. options opt = new BitmapFactory. options (); 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 {// calculate the value of inSampleSize and compress the image 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 that is a power of 2 and keeps both // height and width larger than the requested 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"> <ImageView android: id = "@ + id/writeText_img" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: maxHeight = "360dp" android: adjustViewBounds = "true" android: contentDescription = "@ null"/> <TextView android: id = "@ + id/writeText_image_ TV" android: 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> <EditText android: id = "@ + id/writeText_et" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: layout_marginTop = "8dp" android: hint = "add remarks"/> <Button android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: onClick = "confirm" android: text = "generate image"/> </LinearLayout>
<End>




Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.