我正在使用http://judepereira.com/blog/multi-touch-in-android-translate-scale-and-rotate/此链接代码,仅对imageview非常有用,我希望一次只能进行多个imageview
>package logicstree.selfitextcom;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import com.capricorn.RayMenu;
public class MainActivitySurfaceView extends Activity implements
SurfaceHolder.Callback,OnTouchListener {
TextView testView;
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
PictureCallback rawCallback;
ShutterCallback shutterCallback;
PictureCallback jpegCallback;
/* Drop drag Textview */
ImageView textImage[] = new ImageView[3];
ViewGroup _root;
int _xDelta;
int _yDelta;
// TextView Pinch Zoom
final static float STEP = 200;
float mRatio = 1.0f;
int mBaseDist;
float mBaseRatio;
float fontsize = 13;
private static final String TAG = "Touch";
private static final float MIN_ZOOM = 1f, MAX_ZOOM = 1f;
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
private static final int[] ITEM_DRAWABLES = { R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher };
/*New All */
public float[] lastEvent = null;
private float d = 0f;
private float newRot = 0f;
public static int counterText = 0;
Dialog dialogText;
RelativeLayout.LayoutParams layoutParams;
ArrayList<ImageView> ImageText;
/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_root = (ViewGroup) findViewById(R.id.relativCapture);
layoutParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
ImageText = new ArrayList<ImageView>();
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format(
"/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d("Log", "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Toast.makeText(getApplicationContext(), "Picture Saved", 2000)
.show();
refreshCamera();
}
};
RayMenu rayMenu = (RayMenu) findViewById(R.id.ray_menu);
final int itemCount = ITEM_DRAWABLES.length;
for (int i = 0; i < itemCount; i++) {
ImageView item = new ImageView(this);
item.setImageResource(ITEM_DRAWABLES[i]);
final int position = i;
rayMenu.addItem(item, new OnClickListener() {
@Override
public void onClick(View v) {
if(position == 0)
{
openDialog();
Toast.makeText(MainActivitySurfaceView.this,"Create Text ..... :" + position, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivitySurfaceView.this,
"position:" + position, Toast.LENGTH_SHORT).show();
}
}
});// Add a menu item
}
}
public void captureImage(View v) throws IOException {
// take the picture
camera.takePicture(null, null, jpegCallback);
counterText=0;
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
counterText=0;
super.onBackPressed();
}
public void refreshCamera() {
if (surfaceHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
camera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception e) {
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
refreshCamera();
}
public void surfaceCreated(SurfaceHolder holder) {
try {
// open the camera
camera = Camera.open();
} catch (RuntimeException e) {
// check for exceptions
System.err.println(e);
return;
}
Camera.Parameters param;
param = camera.getParameters();
// modify parameter
param.setPreviewSize(352, 288);
camera.setParameters(param);
try {
// The Surface has been created, now tell the camera where to draw
// the preview.
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception e) {
// check for exceptions
System.err.println(e);
return;
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// stop preview and release camera
camera.stopPreview();
camera.release();
camera = null;
}
public static Bitmap drawText(String text, int textWidth, int textSize) {
// Get text dimensions
TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
textPaint.setStyle(Paint.Style.FILL);
textPaint.setColor(Color.WHITE);
textPaint.setTextSize(textSize);
StaticLayout mTextLayout = new StaticLayout(text, textPaint, textWidth,Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Create bitmap and canvas to draw to
Bitmap b = Bitmap.createBitmap(textWidth, mTextLayout.getHeight(),Config.ARGB_8888);
Canvas c = new Canvas(b);
// Draw background
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
paint.setColor(Color.TRANSPARENT);
c.drawPaint(paint);
// Draw text
c.save();
c.translate(0, 0);
mTextLayout.draw(c);
c.restore();
return b;
}
public void openDialog() {
dialogText = new Dialog(MainActivitySurfaceView.this);
dialogText.setContentView(R.layout.dialog);
dialogText.setTitle("Custom Dialog");
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Test" + counterText++, Toast.LENGTH_SHORT).show();
/* for(final ImageView image : ImageText)
_root.addView(image);
image.setLayoutParams(layoutParams);
image.setScaleType(ScaleType.MATRIX);
image.setOnTouchListener(this);
*/
final EditText txtEdit = (EditText) dialogText.findViewById(R.id.editText1);
Button btnclick = (Button) dialogText.findViewById(R.id.btnClick);
btnclick.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String name = txtEdit.getText().toString();
int width = getWindowManager().getDefaultDisplay().getWidth();
//int size = (int) txtEdit.getTextSize() ;
Bitmap bmp = drawText(name, width, 100);
ImageView inage= new ImageView(MainActivitySurfaceView.this);
inage.setImageBitmap(bmp);
++counterText;
dialogText.dismiss();
_root.addView(inage);
inage.setLayoutParams(layoutParams);
inage.setScaleType(ScaleType.MATRIX);
inage.setOnTouchListener(MainActivitySurfaceView.this);
}
});
dialogText.show();
}
@Override
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
mode = DRAG;
lastEvent = null;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
}
lastEvent = new float[4];
lastEvent[0] = event.getX(0);
lastEvent[1] = event.getX(1);
lastEvent[2] = event.getY(0);
lastEvent[3] = event.getY(1);
d = rotation(event);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
lastEvent = null;
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
matrix.set(savedMatrix);
float dx = event.getX() - start.x;
float dy = event.getY() - start.y;
matrix.postTranslate(dx, dy);
} else if (mode == ZOOM) {
float newDist = spacing(event);
if (newDist > 10f) {
matrix.set(savedMatrix);
float scale = (newDist / oldDist);
/* if(scale > 1.75f)
System.out.println("====== Scale Is : " + scale);
else*/
matrix.postScale(scale, scale, mid.x, mid.y);
}
if (lastEvent != null && event.getPointerCount() == 2) {
newRot = rotation(event);
float r = newRot - d;
float[] values = new float[9];
matrix.getValues(values);
float tx = values[2];
float ty = values[5];
float sx = values[0];
float xc = (view.getWidth() / 2) * sx;
float yc = (view.getHeight() / 2) * sx;
matrix.postRotate(r, mid.x, mid.y);
}
}
break;
}
onTouchEvent(event);
view.setImageMatrix(matrix);
return true;
}
private float rotation(MotionEvent event) {
// TODO Auto-generated method stub
double delta_x = (event.getX(0) - event.getX(1));
double delta_y = (event.getY(0) - event.getY(1));
double radians = Math.atan2(delta_y, delta_x);
return (float) Math.toDegrees(radians);
}
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
private void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
private void dumpEvent(MotionEvent event) {
String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
"POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN
|| actionCode == MotionEvent.ACTION_POINTER_UP) {
sb.append("(pid ").append(
action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i = 0; i < event.getPointerCount(); i++) {
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
sb.append(")=").append((int) event.getX(i));
sb.append(",").append((int) event.getY(i));
if (i + 1 < event.getPointerCount())
sb.append(";");
}
sb.append("]");
Log.d("Touch Events ---------", sb.toString());
}
@Override
public void onDetachedFromWindow() {
// TODO Auto-generated method stub
System.out.println("===onde");
//bm.recycle();
System.gc();
super.onDetachedFromWindow();
}
}
activity_main
<RelativeLayout
android:id="@+id/relativSurface"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/capture"
android:layout_alignParentTop="true" >
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_below="@+id/ray_menu"
android:clickable="false" >
</SurfaceView>
<com.capricorn.RayMenu
android:background="@android:color/black"
android:id="@+id/ray_menu"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:paddingLeft="5dp"
android:paddingRight="5dp" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="@+id/ray_menu"
android:id="@+id/relativCapture"
android:layout_centerHorizontal="true" >
</RelativeLayout>
</RelativeLayout>
<LinearLayout
android:id="@+id/capture"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:clickable="true"
android:gravity="center"
android:onClick="captureImage"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="Capture"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
</RelativeLayout
这是我的dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="24dp"
android:layout_marginTop="30dp"
android:text="Enter Text" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView1"
android:layout_alignBottom="@+id/textView1"
android:layout_marginLeft="10dp"
android:layout_toRightOf="@+id/textView1"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="15dp"
android:text="OK" />
</RelativeLayout>
activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="81dp"
android:background="@null"
android:ems="10" >
</EditText>
</RelativeLayout>