Android development by hand gesture to achieve image drag and drop function

Source: Internet
Author: User
Tags stub

This example enables Android to drag and drop images using gestures. The operation effect is as follows:

The code is as follows Copy Code

Import Android.content.Context;
Import Android.os.Bundle;
Import Android.util.DisplayMetrics;
Import android.view.MotionEvent;
Import Android.view.View;

* Android through gestures to achieve image drag and drop function
* @author Administrator
public class Dragactivity extends activity {
/** called the activity is a. */
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
View view = new Imagedragview (this);

Setcontentview (view);

Class Imagedragview extends View {

private float x1;
private float Y1;
private float x2;
private float y2;

Public Imagedragview {
Super (context);
TODO auto-generated Constructor stub

public boolean ontouchevent (Motionevent event) {
TODO auto-generated Method Stub

Float size = event.getsize ();

int szi = (int) size;
int dxi = Szi >> 12;
int dyit = ((1 << 12)-1);
int dyi = Szi & dyit;

Displaymetrics metrics = getresources (). Getdisplaymetrics ();

FLOAT dx = metrics.widthpixels * DXi/(float) dyit;
float dy = metrics.heightpixels * Dyi/(float) dyit;

X1 = Event.getx ();
Y1 = Event.gety ();

x2 = x1 + dx;
y2 = y1 + dy;

Invalidate ();

return true;

protected void OnDraw (Canvas Canvas) {
TODO auto-generated Method Stub
Super.ondraw (canvas);

float R = (float) math.sqrt ((x1-x2) * (X1-X2) + (Y1-Y2)
* (Y1-Y2))/2;
R = >= r? 100:r;

Paint Paint = new Paint ();
Paint.setcolor (;
Canvas.drawcircle (x1, y1, R, Paint);

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: 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.