只要在圖片範圍之內,文字可隨意點擊移動。
[java]
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; //圖片在螢幕中位置X座標
private static float top = 0; //圖片在螢幕中位置Y座標
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);
}
/**
* 傳回值: Bitmap 參數:原圖片,文字 功能: 根據給定的文字產生相應圖片
*
* @param originalMap
* @param text 文字
* @param x 點擊的X座標
* @param y 點擊的Y座標
* @return
*/ / www.2cto.com
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;
}
}
[java]
package xiaosi.GetTextImage;
import android.app.Activity;
import android.os.Bundle;
public class GetTextImageActivity extends Activity {
/** Called when the activity is first created. */
private GetTextImage get;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
get = new GetTextImage(this);
setContentView(get);
}
}
摘自 落日小屋