I have two questions.
1) I would ideally want this signature for my constructor of a class that extends View, because it works for any kind of layout.
public HexagonView(Context context, float radius, PointF origin, int background, Layout layout) {
But, this cannot work because I have to call the constructor with RelativeLayout like so:
HexagonView hexagon = new HexagonView(this, 75, new PointF(200,300), Color.BLUE, (RelativeLayout) findViewById(R.id.activity_main));
Can this be changed to accept multiple layouts? For example, if(layout instanceof RelativeLayout) then cast it. (That doesn't seem to work)
2) The reason why I am passing the layout is so I can later add views easily to that same parent layout. I have a feeling that this isn't a safe programming practice. Is this okay, or should I be going about this a different way?
Edit: I think I figured out my first question about why I couldn't pass it. I believe it is because I assumed LinearLayout and RelativeLayout extended Layout, but in fact they extend ViewGroup
To capture the signature you have to take a linear or relative layout, you capture its signature in a bitmap by creating the drawing cache enabled true and then get its drawing cache for the layout and store it in a bitmap and then display that bitmap in the imageview.
You can take help from the following code
First create an inner class signature which extends the View
public class signature extends View {
private static final float STROKE_WIDTH = 5f;
private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
private Paint paint = new Paint();
private Path path = new Path();
private float lastTouchX;
private float lastTouchY;
private final RectF dirtyRect = new RectF();
public signature(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(STROKE_WIDTH);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
resetDirtyRect(eventX, eventY);
int historySize = event.getHistorySize();
for (int i = 0; i < historySize; i++) {
float historicalX = event.getHistoricalX(i);
float historicalY = event.getHistoricalY(i);
expandDirtyRect(historicalX, historicalY);
path.lineTo(historicalX, historicalY);
}
path.lineTo(eventX, eventY);
break;
default:
debug("Ignored touch event: " + event.toString());
return false;
}
invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
(int) (dirtyRect.top - HALF_STROKE_WIDTH),
(int) (dirtyRect.right + HALF_STROKE_WIDTH),
(int) (dirtyRect.bottom + HALF_STROKE_WIDTH));
lastTouchX = eventX;
lastTouchY = eventY;
return true;
}
private void debug(String string) {
}
private void expandDirtyRect(float historicalX, float historicalY) {
if (historicalX < dirtyRect.left) {
dirtyRect.left = historicalX;
} else if (historicalX > dirtyRect.right) {
dirtyRect.right = historicalX;
}
if (historicalY < dirtyRect.top) {
dirtyRect.top = historicalY;
} else if (historicalY > dirtyRect.bottom) {
dirtyRect.bottom = historicalY;
}
}
private void resetDirtyRect(float eventX, float eventY) {
dirtyRect.left = Math.min(lastTouchX, eventX);
dirtyRect.right = Math.max(lastTouchX, eventX);
dirtyRect.top = Math.min(lastTouchY, eventY);
dirtyRect.bottom = Math.max(lastTouchY, eventY);
}
}
In the main activity create an object of the class signature like
signature sign;
mLinearSign.addView(sign, LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
and when you want in your program to capture the signature follow the following lines of code
ImageView ImgVwSign;
Bitmap sign = Bitmap.createBitmap(480, 800,Bitmap.Config.ARGB_8888);
mLinearSign.setDrawingCacheEnabled(true);
sign =mContent.getDrawingCache();
ImgVwSign.setImageBitmap(sign );
Related
Here create a function to paint the line in each imageView. There are 4 imageView will use the duplicate code
public class ChildrenActivity extends AppCompatActivity {
ImageView imageView1, imageView2, imageView3, imageView4;
Canvas canvas1, canvas2;
Paint paint;
Bitmap baseBitmap1, baseBitmap2, baseBitmap3, baseBitmap4;
float startX,startY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_children);
imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView3 = (ImageView) findViewById(R.id.imageView3);
imageView4 = (ImageView) findViewById(R.id.imageView4);
Here attached the ImageView1 to implement the painting function. Please advice me to solve the problem.
imageView1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
paint = new Paint();
paint.setStrokeWidth(20);
paint.setColor(Color.BLACK);
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
if (baseBitmap1 == null) {
baseBitmap1 = Bitmap.createBitmap(imageView1.getWidth(), imageView1.getHeight(), Bitmap.Config.ARGB_8888);
canvas1 = new Canvas(baseBitmap1);
canvas1.drawColor(Color.WHITE);
}
startX = motionEvent.getX();
startY = motionEvent.getY();
break;
case MotionEvent.ACTION_MOVE:
float endX = motionEvent.getX();
float endY = motionEvent.getY();
canvas1.drawLine(startX, startY, endX, endY, paint);
startX = motionEvent.getX();
startY = motionEvent.getY();
imageView1.setImageBitmap(baseBitmap1);
break;
}
return true;
}
});
Here attached the ImageView2 to implement the painting function. Please advice me to solve the problem.
imageView2.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
paint = new Paint();
paint.setStrokeWidth(20);
paint.setColor(Color.BLACK);
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
if (baseBitmap2 == null) {
baseBitmap2 = Bitmap.createBitmap(imageView2.getWidth(), imageView2.getHeight(), Bitmap.Config.ARGB_8888);
canvas2 = new Canvas(baseBitmap2);
canvas2.drawColor(Color.WHITE);
}
startX = motionEvent.getX();
startY = motionEvent.getY();
break;
case MotionEvent.ACTION_MOVE:
float endX = motionEvent.getX();
float endY = motionEvent.getY();
canvas2.drawLine(startX, startY, endX, endY, paint);
startX = motionEvent.getX();
startY = motionEvent.getY();
imageView2.setImageBitmap(baseBitmap2);
break;
}
return true;
}
});
}
}
Here got the error message according to Steve comment
I think you just want to extract the listener setups to a method of it's own.
Like this:
public void RegisterImageViewTouchListener(final ImageView imageView, final Bitmap bitmap, final Canvas canvas)
{
imageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
paint = new Paint();
paint.setStrokeWidth(20);
paint.setColor(Color.BLACK);
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
if (bitmap== null) {
bitmap= Bitmap.createBitmap(imageView.getWidth(), imageView.getHeight(), Bitmap.Config.ARGB_8888);
canvas= new Canvas(baseBitmap1);
canvas.drawColor(Color.WHITE);
}
startX = motionEvent.getX();
startY = motionEvent.getY();
break;
case MotionEvent.ACTION_MOVE:
float endX = motionEvent.getX();
float endY = motionEvent.getY();
canvas.drawLine(startX, startY, endX, endY, paint);
startX = motionEvent.getX();
startY = motionEvent.getY();
imageView.setImageBitmap(bitmap);
break;
}
return true;
}
});
}
And then invoke the method, like this:
RegisterImageViewTouchListener(imageView1, baseBitmap1, canvas1);
RegisterImageViewTouchListener(imageView2, baseBitmap2, canvas2);
You could take this one step further and store your ImageView, Bitmap and Canvas objects in an ArrayList and then loop over them whilst calling the method above.
Hope this helps.
I simply want to touch and drag/move an object around on the screen.
I know there are plenty of given codes out there, using surface holder and imageview matrix. But these codes are not well notated, and I don't know what is going on. I want to just copy and paste them into my own code.
I know there is this documentation on Android Dev website that teaches you how to drag and scale. But for dragging, it only gives an example for the onTouchEvent(), but I don't how I can integrate this method into my MainActivity.java and activity_main.xml files. Specically, in the code snippet, there are mPosX and mPosY, and I don't know how to use these global variables.
I tried creating a new class extending View class and put onTouchEvent().
I know you can use onDraw() and override it to utilize mPosX and mPosY to redraw the object every time your finger moves, but how exactly i don't know. I need some example codes implementing onDraw().
This is the code snippet I am talking about:
// The ‘active pointer’ is the one currently moving our object.
private int mActivePointerId = INVALID_POINTER_ID;
#Override
public boolean onTouchEvent(MotionEvent ev) {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector.onTouchEvent(ev);
final int action = MotionEventCompat.getActionMasked(ev);
switch (action) {
case MotionEvent.ACTION_DOWN: {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final float x = MotionEventCompat.getX(ev, pointerIndex);
final float y = MotionEventCompat.getY(ev, pointerIndex);
// Remember where we started (for dragging)
mLastTouchX = x;
mLastTouchY = y;
// Save the ID of this pointer (for dragging)
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
break;
}
case MotionEvent.ACTION_MOVE: {
// Find the index of the active pointer and fetch its position
final int pointerIndex =
MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, pointerIndex);
final float y = MotionEventCompat.getY(ev, pointerIndex);
// Calculate the distance moved
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
mPosX += dx;
mPosY += dy;
invalidate();
// Remember this touch position for the next move event
mLastTouchX = x;
mLastTouchY = y;
break;
}
case MotionEvent.ACTION_UP: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_CANCEL: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = MotionEventCompat.getX(ev, newPointerIndex);
mLastTouchY = MotionEventCompat.getY(ev, newPointerIndex);
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
break;
}
}
return true;
}
Create a class MoveViewTouchListener
public class MoveViewTouchListener
implements View.OnTouchListener
{
private GestureDetector mGestureDetector;
private View mView;
public MoveViewTouchListener(View view)
{
mGestureDetector = new GestureDetector(view.getContext(), mGestureListener);
mView = view;
}
#Override
public boolean onTouch(View v, MotionEvent event)
{
return mGestureDetector.onTouchEvent(event);
}
private GestureDetector.OnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener()
{
private float mMotionDownX, mMotionDownY;
#Override
public boolean onDown(MotionEvent e)
{
mMotionDownX = e.getRawX() - mView.getTranslationX();
mMotionDownY = e.getRawY() - mView.getTranslationY();
Log.d("imageview"," down");
return true;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
{
mView.setTranslationX(e2.getRawX() - mMotionDownX);
mView.setTranslationY(e2.getRawY() - mMotionDownY);
if((distanceX==0)&&(distanceY==0))
{
Log.d("imageview"," zoomed");
}
return true;
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
Log.d("imageview"," tapped");
return true;
}
};
}
In activity call:
ImageView imageView= findViewById(R.id.imageView);
imageView.setOnTouchListener(new MoveViewTouchListener(imageView));
I try to make image editor application. in this application i try to put multiple sticker on image that sticker can move , zoom , rotate, and also selected sticker can erase . can anyone help me ? here is code that i done with sticker move,rotate,zoom but i cant erase selected sticker .
public class MainActivity extends AppCompatActivity {
Bitmap originalBitmap,originalBitmap1;
RelativeLayout rlImageViewContainer;
private ImageView ivRedo;
private ImageView ivUndo;
Button btn_erase;
private ArrayList<Path> paths;
private ArrayList<Path> redoPaths;
Paint destPaint = new Paint();
Path destPath = new Path();
Bitmap destBitmap;
Canvas destCanvas = new Canvas();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a);
originalBitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.b);
initView();
}
private void initView() {
ivUndo = (ImageView) findViewById(R.id.iv_undo);
ivRedo = (ImageView) findViewById(R.id.iv_redo);
rlImageViewContainer = findViewById(R.id.rl_image_view_container);
final PhotoSortrView photoSortrView = new PhotoSortrView(this);
rlImageViewContainer.addView(photoSortrView,0);
photoSortrView.setBackgroundColor(getResources().getColor(R.color.tran));
photoSortrView.addImages(this, originalBitmap);
photoSortrView.addImages(this, originalBitmap1);
ivUndo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// undo();
}
});
ivRedo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// redo();
}
});
btn_erase = (Button) findViewById(R.id.btn_erase);
btn_erase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (photoSortrView.isErase) {
btn_erase.setBackgroundColor(Color.RED);
photoSortrView.isErase = false;
photoSortrView.isMove = true;
} else {
btn_erase.setBackgroundColor(Color.GREEN);
photoSortrView.isErase = true;
photoSortrView.isMove = false;
}
}
});
}
}
PhotoSortrView.java
public class PhotoSortrView extends View implements MultiTouchController.MultiTouchObjectCanvas<MultiTouchEntity> {
private static final String TAG = "PhotoSortr ####### ";
// private static final int[] IMAGES = { R.drawable.m74hubble };
private Path drawPath = new Path();
// drawing and canvas paint
private Paint drawPaint = new Paint(), canvasPaint = new Paint();
// initial color
private int paintColor = Color.TRANSPARENT;
// canvas
private Canvas drawCanvas = new Canvas();
// canvas bitmap
private Bitmap canvasBitmap;
private ArrayList<MultiTouchEntity> imageIDs = new ArrayList<MultiTouchEntity>();
// --
private MultiTouchController<MultiTouchEntity> multiTouchController = new MultiTouchController<MultiTouchEntity>(this);
// --
private MultiTouchController.PointInfo currTouchPoint = new MultiTouchController.PointInfo();
private static final int UI_MODE_ROTATE = 1, UI_MODE_ANISOTROPIC_SCALE = 2;
private int mUIMode = UI_MODE_ROTATE;
// --
private static final float SCREEN_MARGIN = 100;
private int displayWidth, displayHeight;
public boolean isErase = false;
public boolean isMove = true;
Paint destPaint = new Paint();
Path destPath = new Path();
Bitmap destBitmap;
Canvas destCanvas = new Canvas();
int height,width;
// ---------------------------------------------------------------------------------------------------
public PhotoSortrView(Context context) {
this(context, null);
setupPaint();
init(context);
}
private void setupPaint() {
destPaint.setAlpha(0);
destPaint.setAntiAlias(true);
destPaint.setStyle(Paint.Style.STROKE);
destPaint.setStrokeJoin(Paint.Join.ROUND);
destPaint.setStrokeCap(Paint.Cap.ROUND);
destPaint.setStrokeWidth(20);
destPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
}
public PhotoSortrView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
setupDrawing();
}
public PhotoSortrView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
Log.e(TAG, "init: " );
Resources res = context.getResources();
setBackgroundColor(Color.TRANSPARENT);
DisplayMetrics metrics = res.getDisplayMetrics();
this.displayWidth = res.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? Math
.max(metrics.widthPixels, metrics.heightPixels) : Math.min(
metrics.widthPixels, metrics.heightPixels);
this.displayHeight = res.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? Math
.min(metrics.widthPixels, metrics.heightPixels) : Math.max(
metrics.widthPixels, metrics.heightPixels);
}
public void addImages(Context context, Bitmap resourceId) {
Log.e(TAG, "addImages: " );
// setupDrawing();
Resources res = context.getResources();
imageIDs.add(new ImageEntity(resourceId, res));
float cx = SCREEN_MARGIN + (float)
(Math.random() * (displayWidth - 2 * SCREEN_MARGIN));
float cy = SCREEN_MARGIN + (float)
(Math.random() * (displayHeight - 2 * SCREEN_MARGIN));
imageIDs.get(imageIDs.size() - 1).load(context, cx, cy);
invalidate();
}
public void removeAllImages() {
imageIDs.removeAll(imageIDs);
invalidate();
}
public void removeImage() {
if (imageIDs.size() > 0) {
imageIDs.remove(imageIDs.size() - 1);
}
invalidate();
}
public int getCountImage() {
return imageIDs.size();
}
// ---------------------------------------------------------------------------------------------------
#Override
protected void onDraw(Canvas canvas) {
Log.e(TAG, "onDraw: " );
if (isErase){
Log.e(TAG, "onDraw: isErase" );
if (destBitmap != null){
destCanvas.drawPath(destPath,destPaint);
canvas.drawBitmap(destBitmap,0,0,null);
}
}
else if (isMove){
height = imageIDs.get(0).getHeight();
width = imageIDs.get(0).getWidth();
Log.e(TAG, "onDraw: isMove");
canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
canvas.drawPath(drawPath,drawPaint);
int n = imageIDs.size();
for (int i = 0; i < n; i++)
imageIDs.get(i).draw(canvas);
}
super.onDraw(canvas);
}
// ---------------------------------------------------------------------------------------------------
public void trackballClicked() {
mUIMode = (mUIMode + 1) % 3;
invalidate();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//collegeActivity.set
int action = event.getAction();
Log.e(TAG, "onTouchEvent: " );
float touchX = event.getX();
float touchY = event.getY();
// respond to down, move and up events
if (isErase){
Log.e(TAG, "onTouchEvent: isErase" );
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
destPath.moveTo(touchX,touchY);
break;
case MotionEvent.ACTION_MOVE:
destPath.lineTo(touchX,touchY);
break;
}
} else if (isMove) {
Log.e(TAG, "onTouchEvent: isMove" );
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
drawPath.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
drawPath.lineTo(touchX, touchY);
break;
case MotionEvent.ACTION_UP:
drawPath.lineTo(touchX, touchY);
drawCanvas.drawPath(drawPath, drawPaint);
drawPath.reset();
break;
default:
return false;
}
return multiTouchController.onTouchEvent(event);
}
invalidate();
return true;
}
private void setupDrawing() {
Log.e(TAG, "setupDrawing: " );
// prepare for drawing and setup paint stroke properties
drawPath = new Path();
drawPaint.setAlpha(0);
drawPaint.setColor(0);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(10);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint = new Paint(Paint.DITHER_FLAG);
}
// size assigned to view
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (w > 0 && h > 0) {
Log.e(TAG, "onSizeChanged: " );
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
drawCanvas = new Canvas(canvasBitmap);
}
}
// update color
public void setColor(String newColor) {
Log.e(TAG, "setColor: " );
invalidate();
paintColor = Color.parseColor(newColor);
drawPaint.setColor(paintColor);
}
public MultiTouchEntity getDraggableObjectAtPoint(MultiTouchController.PointInfo pt) {
float x = pt.getX(), y = pt.getY();
int n = imageIDs.size();
for (int i = n - 1; i >= 0; i--) {
ImageEntity im = (ImageEntity) imageIDs.get(i);
if (im.containsPoint(x, y))
return im;
}
return null;
}
public void selectObject(MultiTouchEntity img, MultiTouchController.PointInfo touchPoint) {
currTouchPoint.set(touchPoint);
if (img != null) {
// Move image to the top of the stack when selected
drawPaint.setColor(Color.TRANSPARENT);
imageIDs.remove(img);
imageIDs.add(img);
destCanvas = new Canvas();
destBitmap = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
destCanvas.setBitmap(destBitmap);
destCanvas.drawBitmap(img.getBitmap(),0,0,null);
} else {
// Called with img == null when drag stops.
}
invalidate();
}
public void getPositionAndScale(MultiTouchEntity img, MultiTouchController.PositionAndScale objPosAndScaleOut) {
// requires averaging the two scale factors)
objPosAndScaleOut.set(img.getCenterX(), img.getCenterY(),
(mUIMode & UI_MODE_ANISOTROPIC_SCALE) == 0,
(img.getScaleX() + img.getScaleY()) / 2,
(mUIMode & UI_MODE_ANISOTROPIC_SCALE) != 0, img.getScaleX(),
img.getScaleY(), (mUIMode & UI_MODE_ROTATE) != 0,
img.getAngle());
}
/**
* Set the position and scale of the dragged/stretched image.
*/
public boolean setPositionAndScale(MultiTouchEntity img,
MultiTouchController.PositionAndScale newImgPosAndScale, MultiTouchController.PointInfo touchPoint) {
currTouchPoint.set(touchPoint);
boolean ok = img.setPos(newImgPosAndScale);
if (ok)
invalidate();
return ok;
}
public boolean pointInObjectGrabArea(MultiTouchController.PointInfo pt, MultiTouchEntity img) {
return false;
}
}
I used this to perform pinch zoom and drag.
public class ZoomLayout extends FrameLayout implements ScaleGestureDetector.OnScaleGestureListener {
private enum Mode {
NONE,
DRAG,
ZOOM
}
private static final String TAG = "ZoomLayout";
private static final float MIN_ZOOM = 1.0f;
private static final float MAX_ZOOM = 4.0f;
private Mode mode = Mode.NONE;
private float scale = 1.0f;
private float lastScaleFactor = 0f;
// Where the finger first touches the screen
private float startX = 0f;
private float startY = 0f;
// How much to translate the canvas
private float dx = 0f;
private float dy = 0f;
private float prevDx = 0f;
private float prevDy = 0f;
public ZoomLayout(Context context) {
super(context);
init(context);
}
public ZoomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ZoomLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
final ScaleGestureDetector scaleDetector = new ScaleGestureDetector(context, this);
this.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "DOWN");
if (scale > MIN_ZOOM) {
mode = Mode.DRAG;
startX = motionEvent.getX() - prevDx;
startY = motionEvent.getY() - prevDy;
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == Mode.DRAG) {
dx = motionEvent.getX() - startX;
dy = motionEvent.getY() - startY;
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
mode = Mode.ZOOM;
break;
case MotionEvent.ACTION_POINTER_UP:
mode = Mode.DRAG;
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "UP");
mode = Mode.NONE;
prevDx = dx;
prevDy = dy;
break;
}
scaleDetector.onTouchEvent(motionEvent);
if ((mode == Mode.DRAG && scale >= MIN_ZOOM) || mode == Mode.ZOOM) {
getParent().requestDisallowInterceptTouchEvent(true);
float maxDx = (child().getWidth() - (child().getWidth() / scale)) / 2 * scale;
float maxDy = (child().getHeight() - (child().getHeight() / scale))/ 2 * scale;
dx = Math.min(Math.max(dx, -maxDx), maxDx);
dy = Math.min(Math.max(dy, -maxDy), maxDy);
Log.i(TAG, "Width: " + child().getWidth() + ", scale " + scale + ", dx " + dx
+ ", max " + maxDx);
applyScaleAndTranslation();
}
return true;
}
});
}
// ScaleGestureDetector
#Override
public boolean onScaleBegin(ScaleGestureDetector scaleDetector) {
Log.i(TAG, "onScaleBegin");
return true;
}
#Override
public boolean onScale(ScaleGestureDetector scaleDetector) {
float scaleFactor = scaleDetector.getScaleFactor();
Log.i(TAG, "onScale" + scaleFactor);
if (lastScaleFactor == 0 || (Math.signum(scaleFactor) == Math.signum(lastScaleFactor))) {
scale *= scaleFactor;
scale = Math.max(MIN_ZOOM, Math.min(scale, MAX_ZOOM));
lastScaleFactor = scaleFactor;
} else {
lastScaleFactor = 0;
}
return true;
}
#Override
public void onScaleEnd(ScaleGestureDetector scaleDetector) {
Log.i(TAG, "onScaleEnd");
}
private void applyScaleAndTranslation() {
child().setScaleX(scale);
child().setScaleY(scale);
child().setTranslationX(dx);
child().setTranslationY(dy);
}
private View child() {
return getChildAt(0);
}
}
The problem that I am having with this is that when I zoom in, then drag, it snaps to the middle of the screen. I think the problem lies at:
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "DOWN");
if (scale > MIN_ZOOM) {
mode = Mode.DRAG;
startX = motionEvent.getX() - prevDx;
startY = motionEvent.getY() - prevDy;
}
break;
I am not sure how to fix this, can anyone please help me?
I fixed it by changing onScale to:
public boolean onScale(ScaleGestureDetector scaleDetector) {
float scaleFactor = scaleDetector.getScaleFactor();
Log.i(TAG, "mode:" + this.mode + ", onScale:" + scaleFactor);
if (this.lastScaleFactor == 0.0f || Math.signum(scaleFactor) == Math.signum(this.lastScaleFactor)) {
this.scale *= scaleFactor;
this.scale = Math.max(MIN_ZOOM, Math.min(this.scale, MAX_ZOOM));
this.lastScaleFactor = scaleFactor;
} else {
this.lastScaleFactor = 0.0f;
}
if (this.mSurfaceView != null) {
int orgWidth = getWidth();
int _width = (int) (((float) orgWidth) * this.scale);
int _height = (int) (((float) getHeight()) * this.scale);
LogUtil.b(new StringBuilder(String.valueOf(_width)).append(", ").append(_height).toString());
LayoutParams params = (LayoutParams) this.mSurfaceView.getLayoutParams();
params.height = _height;
params.width = _width;
this.mSurfaceView.setLayoutParams(params);
child().setScaleX(this.scale);
child().setScaleY(this.scale);
}
return true;
}
In my android app, I have a crop image. So, I programming a custom view as my crop box. I can move the crop box. But my problem is how can I drag border of the crop box and change width and height of it. How can I do it?
Attr Class:
public class Attr {
public static final float CROP_BOX_START_X = 5;
public static final float CROP_BOX_START_Y = 5;
public static final float CROP_BOX_END_X = 305;
public static final float CROP_BOX_END_Y = 105;
}
CropBox Class:
public class CropBox extends View {
private Paint paint = new Paint();
public CropBox(Context context) {
super(context);
}
public CropBox(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
#Override
public void onDraw(Canvas canvas) {
float[][] circleXY = {
{Attr.CROP_BOX_START_X, Attr.CROP_BOX_START_Y},
{(Attr.CROP_BOX_START_X + Attr.CROP_BOX_END_X) / 2, Attr.CROP_BOX_START_Y},
{Attr.CROP_BOX_END_X, Attr.CROP_BOX_START_Y},
{Attr.CROP_BOX_START_X, Attr.CROP_BOX_END_Y},
{(Attr.CROP_BOX_START_X + Attr.CROP_BOX_END_X) / 2, Attr.CROP_BOX_END_Y},
{Attr.CROP_BOX_END_X, Attr.CROP_BOX_END_Y},
{Attr.CROP_BOX_START_X, (Attr.CROP_BOX_START_Y + Attr.CROP_BOX_END_Y) / 2},
{Attr.CROP_BOX_END_X, (Attr.CROP_BOX_START_Y + Attr.CROP_BOX_END_Y) / 2}
};
float[][] lineXY = {
{Attr.CROP_BOX_START_X, Attr.CROP_BOX_START_Y, Attr.CROP_BOX_END_X, Attr.CROP_BOX_START_Y},
{Attr.CROP_BOX_START_X, Attr.CROP_BOX_END_Y, Attr.CROP_BOX_END_X, Attr.CROP_BOX_END_Y},
{Attr.CROP_BOX_START_X, Attr.CROP_BOX_START_Y, Attr.CROP_BOX_START_X, Attr.CROP_BOX_END_Y},
{Attr.CROP_BOX_END_X, Attr.CROP_BOX_START_Y, Attr.CROP_BOX_END_X, Attr.CROP_BOX_END_Y}
};
paint.setColor(Color.CYAN);
paint.setStrokeWidth(1);
for(int i = 0 ; i < circleXY.length ; i++)
canvas.drawCircle(circleXY[i][0], circleXY[i][1], 5, paint);
paint.setStrokeWidth(2);
for(int i = 0 ; i < lineXY.length ; i++)
canvas.drawLine(lineXY[i][0], lineXY[i][2], lineXY[i][2], lineXY[i][3], paint);
}
}
CropTestActivity Class:
public class CropTestActivity extends Activity {
private ImageView imageView;
private CropBox cropBox;
private RelativeLayout relativeLayout;
private RelativeLayout.LayoutParams layoutParams;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.crop_test_layout);
imageView = (ImageView)findViewById(R.id.android_image);
cropBox = new CropBox(this);
relativeLayout = (RelativeLayout)findViewById(R.id.crop_test_layout);
layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
imageView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
layoutParams.leftMargin = imageView.getWidth() / 2 - (int)((Attr.CROP_BOX_START_X + Attr.CROP_BOX_END_X) / 2) + imageView.getLeft();
layoutParams.topMargin = imageView.getHeight() / 2 - (int)((Attr.CROP_BOX_START_Y + Attr.CROP_BOX_END_Y) / 2) + imageView.getTop();
}
});
relativeLayout.addView(cropBox, layoutParams);
cropBox.setOnTouchListener(new Crop(imageView));
}
}
Crop Class:
public class Crop implements OnTouchListener {
private static final int NONE = 0;
private static final int BOX_DRAG = 1;
private static final int BORDER_DRAG = 2;
private int mode = NONE;
private float cropBoxStartX = Attr.CROP_BOX_START_X;
private float cropBoxStartY = Attr.CROP_BOX_START_Y;
private float cropBoxEndX = Attr.CROP_BOX_END_X;
private float cropBoxEndY = Attr.CROP_BOX_END_Y;
private ImageView imageView;
private PointF start = new PointF();
public Crop(ImageView imageView) {
this.imageView = imageView;
}
public boolean onTouch(View view, MotionEvent event) {
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)view.getLayoutParams();
switch(event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
start.set(event.getX(), event.getY());
if(event.getX() > cropBoxStartX && event.getX() < cropBoxEndX && event.getY() > cropBoxStartY && event.getY() < cropBoxEndY)
mode = BOX_DRAG;
else if(event.getX() == cropBoxStartX || event.getX() == cropBoxEndX || event.getY() == cropBoxStartY || event.getY() == cropBoxEndY)
mode = BORDER_DRAG;
else
mode = NONE;
break;
case MotionEvent.ACTION_UP:
mode = NONE;
break;
case MotionEvent.ACTION_MOVE:
if(mode == BOX_DRAG) {
layoutParams.leftMargin = (int)event.getX() - (int)start.x + view.getLeft();
layoutParams.topMargin = (int)event.getY() - (int)start.y + view.getTop();
while(layoutParams.topMargin + 5 < imageView.getTop())
layoutParams.topMargin++;
while(layoutParams.leftMargin + (cropBoxEndX - cropBoxStartX + 5) > imageView.getRight())
layoutParams.leftMargin--;
while(layoutParams.topMargin + (cropBoxEndY - cropBoxStartY + 5) > imageView.getBottom())
layoutParams.topMargin--;
while(layoutParams.leftMargin + 5 < imageView.getLeft())
layoutParams.leftMargin++;
}
else if(mode == BORDER_DRAG) {
}
break;
}
view.setLayoutParams(layoutParams);
return true;
}
}
Layout XML:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/crop_test_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/android_image"
android:src="#drawable/android"
android:layout_width="fill_parent"
android:layout_height="300dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_gravity="center"
android:scaleType="fitXY"
android:contentDescription="#string/android_image_description" >
</ImageView>
</RelativeLayout>
Before Resize:
After Resize:
Thanks for your help.
Following is the solution,
Modified onCreate from Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.crop_test_layout);
imageView = (ImageView)findViewById(R.id.android_image);
cropBox = new CropBox(this, imageView);
relativeLayout = (RelativeLayout)findViewById(R.id.crop_test_layout);
relativeLayout.addView(cropBox);
}
Modified CropBox class:
public class CropBox extends View {
private static final int CROP_BOX_START_X = 5;
private static final int CROP_BOX_START_Y = 5;
private static final int CROP_BOX_END_X = 305;
private static final int CROP_BOX_END_Y = 105;
private static final int DRAG_SQUARE = 75;
public ImageView mImageView;
boolean mIsFirstClick = false;
private Paint paint = new Paint();
private Rect mRect;
public CropBox(Context context, ImageView aBaseView) {
super(context);
mImageView = aBaseView;
mRect = new Rect(CROP_BOX_START_X, CROP_BOX_START_Y, CROP_BOX_END_X, CROP_BOX_END_Y);
setOnTouchListener(new Crop());
}
public CropBox(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
#Override
public void onDraw(Canvas canvas) {
paint.setStrokeWidth(2);
paint.setColor(Color.CYAN);
paint.setStyle(Paint.Style.STROKE);
canvas.drawRect(mRect, paint);
canvas.drawLine(mRect.right-DRAG_SQUARE, mRect.bottom-DRAG_SQUARE,
mRect.right, mRect.bottom-DRAG_SQUARE, paint);
canvas.drawLine(mRect.right-DRAG_SQUARE, mRect.bottom-DRAG_SQUARE,
mRect.right-DRAG_SQUARE, mRect.bottom, paint);
}
class Crop implements OnTouchListener {
private static final int NONE = 0;
private static final int BOX_DRAG = 1;
private static final int BORDER_DRAG = 2;
private int mode = NONE;
private PointF start = new PointF();
public boolean onTouch(View view, MotionEvent event) {
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)view.getLayoutParams();
switch(event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
start.set(event.getX(), event.getY());
if((event.getX() <= mRect.right && event.getX() >=(mRect.right - DRAG_SQUARE))
&& (event.getY() >= mRect.top && event.getY() >=(mRect.bottom - DRAG_SQUARE))){
mode = BORDER_DRAG;
mIsFirstClick = false;
}
else if(mRect.contains((int)event.getX(), (int)event.getY())) {
mode = BOX_DRAG;
if (mIsFirstClick){
mRect = new Rect(CROP_BOX_START_X, CROP_BOX_START_Y,
CROP_BOX_END_X, CROP_BOX_END_Y);
mIsFirstClick = false;
} else {
mIsFirstClick = true;
}
}
else{
mode = NONE;
mIsFirstClick = true;
}
break;
case MotionEvent.ACTION_UP:
mode = NONE;
break;
case MotionEvent.ACTION_MOVE:
mIsFirstClick = false;
if(mode == BOX_DRAG) {
layoutParams.leftMargin = (int)event.getX() - (int)start.x + view.getLeft();
layoutParams.topMargin = (int)event.getY() - (int)start.y + view.getTop();
}
else if(mode == BORDER_DRAG) {
if (event.getX() > view.getLeft() && event.getY() > view.getTop()){
mRect.right = (int) event.getX();
mRect.bottom = (int) event.getY();
}
}
while(layoutParams.topMargin + 5 < mImageView.getTop())
layoutParams.topMargin++;
while(layoutParams.leftMargin + mRect.right > mImageView.getRight())
layoutParams.leftMargin--;
while(layoutParams.topMargin + mRect.bottom > mImageView.getBottom())
layoutParams.topMargin--;
while(layoutParams.leftMargin + 5 < mImageView.getLeft())
layoutParams.leftMargin++;
break;
}
view.setLayoutParams(layoutParams);
invalidate();
return true;
}
}
}
Some points I would like to mention.
Merged Attr and Crop in CropBox
No need of creating a rectangle from lines. You can use Rect.
Never initialize an array/object in Draw method
Added a feature: if double touched on rectangle it returns to original position
There might be some hitches about the restricting the rect in imageview. I am sure you can fix those... :)
Other than this there is another interesting way using scaling of canvas Image in Canvas with touch events
Use that class instead of Cropbox and try it.
Hope it helps..