使用canvas android进行双向滚动

时间:2014-07-25 13:08:54

标签: java android android-canvas bitmapimage

我使用画布在大图像上绘制了一个标记图像,该图像也是由画布绘制的,但是当我滚动图像时,标记图像不会像Google地图一样同时移动图像。它有什么解决方案吗?

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/table"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent" >

 <HorizontalScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:contentDescription="hello" />
    </ScrollView>
</HorizontalScrollView>

ImageViewFromURLActivity.java

 package com.example.image;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint; 
import android.graphics.Rect;
import android.os.AsyncTask; 
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener; 
import android.view.WindowManager;
import android.widget.ImageView;

   public class ImageViewFromURLActivity extends Activity {
    private static int displayWidth = 0;
    private static int displayHeight = 0;
    public static final String URL = "http://goo.gl/plT1wB";
    static float mX=100;
    static float mY=200;
    ImageView imageView;
    static Bitmap abc = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Create an object for subclass of AsyncTask
    GetXMLTask task = new GetXMLTask();
    // Execute the task
    task.execute(new String[] { URL });
}

private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {

    ProgressDialog dialog = new ProgressDialog(
            ImageViewFromURLActivity.this);

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

        dialog.show();
        dialog.setMessage("Please Wait...");
        dialog.setCancelable(false);

    }

    @Override
    protected Bitmap doInBackground(String... urls) {
        Bitmap map = null;
        for (String url : urls) {
            map = downloadImage(url);
        }
        return map;
    }

    // Sets the Bitmap returned by doInBackground
    @Override
    protected void onPostExecute(Bitmap result) {
        // imageView.setImageBitmap(result);
        Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay();
        displayWidth = display.getWidth();
        displayHeight = display.getHeight();
        System.out.println(displayHeight + "==Height");
        System.out.println(displayWidth + "==width");
        abc = result;
        // SampleView constructor must be constructed last as it needs the
        // displayWidth and displayHeight we just got.

        dialog.dismiss();
        setContentView(new SampleView(ImageViewFromURLActivity.this));
    }

    // Creates Bitmap from InputStream and returns it
    private Bitmap downloadImage(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;

        try {
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
            stream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return bitmap;
    }

    // Makes HttpURLConnection and returns InputStream
    private InputStream getHttpConnection(String urlString)
            throws IOException {
        InputStream stream = null;
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        try {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                stream = httpConnection.getInputStream();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return stream;
    }
}

private static class SampleView extends View {


    private static Bitmap bmLargeImage; // bitmap large enough to be
    // scrolled
    private static Rect displayRect = null; // rect we display to
    private Rect scrollRect = null; // rect we scroll over our bitmap
    private int scrollRectX = 0; // current left location of scroll rect
    private int scrollRectY = 0; // current top location of scroll rect
    private float scrollByX = 0; // x amount to scroll by
    private float scrollByY = 0; // y amount to scroll by
    private float startX = 0; // track x from one ACTION_MOVE to the
    // next
    private float startY = 0; // track y from one ACTION_MOVE to the
     Bitmap largeIcon= BitmapFactory.decodeResource(getResources(), R.drawable.marker);
    // next

    public SampleView(Context context) {
        super(context);

        // Destination rect for our main canvas draw. It never changes.
        displayRect = new Rect(0, 0, displayWidth, displayHeight);


        // Scroll rect: this will be used to 'scroll around' over the
        // bitmap in memory. Initialize as above.
        scrollRect = new Rect(0, 0, displayWidth, displayHeight);

        // Load a large bitmap into an offscreen area of memory.
        bmLargeImage = abc;     

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            // Remember our initial down event location.
            startX = event.getRawX();   
            startY = event.getRawY();

            System.out.println("move action_Start X==" + startX);
            System.out.println(" move action_Start Y==" + startY);


            break;

        case MotionEvent.ACTION_MOVE:

            float x = event.getRawX();
            float y = event.getRawY();
            System.out.println("float x......"+x);
            System.out.println("float y......"+y);



            // Calculate move update. This will happen many times
            // during the course of a single movement gesture.
            scrollByX = x - startX; // move update x increment

            System.out.println("start X....."+startX);
            System.out.println("scroll by X= float x - startX=====" + scrollByX);
            System.out.println("......................");

            scrollByY = y - startY; // move update y increment
            System.out.println("start Y....."+startY);
            System.out.println("scroll by Y= float y - startY=====" + scrollByY);

            startX = x; // reset initial values to latest
            startY = y;
            invalidate(); // force a redraw
            break;
        }
        return true; // done with this event so consume it
    }

    @Override
    protected void onDraw(Canvas canvas) {


        int newScrollRectX = scrollRectX - (int) scrollByX;
        int newScrollRectY = scrollRectY - (int) scrollByY;

        // Don't scroll off the left or right edges of the bitmap.
        if (newScrollRectX < 0)
            newScrollRectX = 0;
        else if (newScrollRectX > (bmLargeImage.getWidth() - displayWidth))
            newScrollRectX = (bmLargeImage.getWidth() - displayWidth);

        // Don't scroll off the top or bottom edges of the bitmap.
        if (newScrollRectY < 0)
            newScrollRectY = 0;
        else if (newScrollRectY > (bmLargeImage.getHeight() - displayHeight))
            newScrollRectY = (bmLargeImage.getHeight() - displayHeight);

        // We have our updated scroll rect coordinates, set them and
        // draw.
        scrollRect.set(newScrollRectX, newScrollRectY, newScrollRectX + displayWidth, newScrollRectY + displayHeight);
        Paint paint = new Paint();
        canvas.drawBitmap(bmLargeImage, scrollRect, displayRect, paint);
        scrollRectX = newScrollRectX;
        scrollRectY = newScrollRectY;

        canvas.drawBitmap(largeIcon,mX,mY,null);

    }

    }

     }



     o/p:  http://i.imgur.com/c3vapIm.png?1

0 个答案:

没有答案