
只要在图片范围之内,文字可随意点击移动。
- package xiaosi.GetTextImage;
-
-
- import android.content.Context;
- import android.content.res.Resources;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Canvas;
- import android.graphics.Paint;
- import android.util.DisplayMetrics;
- import android.view.MotionEvent;
- import android.view.View;
- import android.view.WindowManager;
-
- public class GetTextImage extends View
- {
- private float x = 20, y = 40;
- private static float windowWidth;
- private static float windowHeight;
- private static float left = 0;
- private static float top = 0;
- private String str = "我爱你";
- private DisplayMetrics dm = new DisplayMetrics();
- private WindowManager windowManager;
- private Bitmap newbitmap;
-
- public GetTextImage(Context context)
- {
- super(context);
- windowManager = (WindowManager) context
- .getSystemService(Context.WINDOW_SERVICE);
-
- windowWidth = windowManager.getDefaultDisplay().getWidth();
-
- windowHeight = windowManager.getDefaultDisplay().getHeight();
- }
-
- public void onDraw(Canvas canvas)
- {
- Resources res = getResources();
- Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.b);
- newbitmap = getTextImage(bmp, str, x, y);
- canvas.drawBitmap(newbitmap, 0, 0, null);
- }
-
- public static Bitmap getTextImage(Bitmap originalMap, String text, float x,
- float y)
- {
- float bitmapWidth = originalMap.getWidth();
- float bitmapHeight = originalMap.getHeight();
-
- Canvas canvas = new Canvas(originalMap);
-
- Paint paint = new Paint();
-
- float textWidth = paint.measureText(text);
- canvas.drawBitmap(originalMap, 0, 0, null);
-
-
- if (left + bitmapWidth < windowWidth)
- {
-
- if (x >= left + bitmapWidth - textWidth)
- {
- x = left + bitmapWidth - textWidth;
- }
-
- else if (x <= left)
- {
- x = left;
- }
- }
- else
- {
-
- if (x >= windowWidth - textWidth)
- {
- x = windowWidth - textWidth;
- }
-
- else if (x <= 0)
- {
- x = 0;
- }
- }
-
- if (top + bitmapHeight < windowHeight)
- {
-
- if (y >= top + bitmapHeight)
- {
- y = top + bitmapHeight;
- }
-
- else if (y <= top + 10)
- {
- y = top + 10;
- }
- }
- else
- {
- if (y >= windowHeight)
- {
- y = windowHeight;
- }
- else if (y <= 0)
- {
- y = 0;
- }
- }
-
-
- canvas.drawText(text, x, y, paint);
- return originalMap;
- }
- @Override
- public boolean onTouchEvent(MotionEvent event)
- {
- if (event.getAction() == MotionEvent.ACTION_DOWN)
- {
- x = event.getX();
- y = event.getY();
-
- invalidate();
- }
- return true;
- }
- }
- package xiaosi.GetTextImage;
-
- import android.app.Activity;
- import android.os.Bundle;
-
- public class GetTextImageActivity extends Activity {
-
- private GetTextImage get;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- get = new GetTextImage(this);
- setContentView(get);
- }
- }
Android开发经验之在图片上随意点击移动文字
原文:http://www.cnblogs.com/Free-Thinker/p/6722199.html