将位图转换为imageview以使用ontouchlistener进行拖放

时间:2017-04-19 13:08:18

标签: android bitmap nullpointerexception

我试图将已经绘制到屏幕的位图转换为imageView,以便我可以启用拖动和放大放下它的方法..这是我认为我可以实现这一点的唯一方法。

I尝试将加载的位图(hazardCard)加载到名为cardImage1的imageview中。

代码:

public class PlayScreen extends GameScreen {


   // /////////////////////////////////////////////////////////////////////////
    // Properties
    // /////////////////////////////////////////////////////////////////////////
    private Rect backButtonBound;
    private Rect hazardCardBound;

    private Music screenClickMusic;


    /**
     * Width and height of the level
     */
   // private final float LEVEL_WIDTH = 1000.0f;
    //private final float LEVEL_HEIGHT = 1000.0f;

    /**
     * Define viewports for this layer and the associated screen projection
     */
    private ScreenViewport mScreenViewport;
    private LayerViewport mLayerViewport;

    private Bitmap backgroundBitmap;
    private Bitmap backButton;
    private Bitmap PlayScreenTitle;
    private Bitmap hazardCard;
    private Rect frontLayerBound;
    private Rect playScreenTitleBound;

    private ImageView cardImage1;
    private ViewGroup rootLayout;
    private int _xDelta;
    private int _yDelta;
    public View view;

    /**
     * User input controls for managing the player and the game
     */
   // protected InputControl pauseButton

    // /////////////////////////////////////////////////////////////////////////
    // Constructors
    // /////////////////////////////////////////////////////////////////////////

    /**
     * Create a game
     *
     * @param game
     *            Game to which this screen belongs */

    public PlayScreen(Game game) {
        super("PlayScreen", game);

        //Define the rects what will be used to 'hold' the images
        int spacingX = game.getScreenWidth() / 8;
        int spacingY = game.getScreenHeight() / 8;
        int padding = spacingY / 10;    //padding between each button
        int line = 1;   //each button is on a new 'line' (under each other)


        // Load in the assets used by the demo
        AssetStore assetManager = game.getAssetManager();
        assetManager.loadAndAddBitmap("pitch", "img/pitch.png");
        assetManager.loadAndAddBitmap("backButton", "img/back_button.png");
        assetManager.loadAndAddBitmap("hazardCard", "img/hazard_card.jpg");


        // Define Rectangles for Bitmaps
       // playScreenTitleBound = new Rect(spacingX * 2, spacingY * 0, spacingX * 6, spacingY * 1);

        this.backgroundBitmap = assetManager.getBitmap("pitch");
        this.backButton = assetManager.getBitmap("backButton");
        this.hazardCard = assetManager.getBitmap("hazardCard");

        //load in sounds
        assetManager.loadAndAddMusic("screenClickMusic", "music/buttonPress.mp3");

        //initialise
        this.screenClickMusic = assetManager.getMusic("screenClickMusic");

    }

    // /////////////////////////////////////////////////////////////////////////
    // Support methods
    // /////////////////////////////////////////////////////////////////////////

    // /////////////////////////////////////////////////////////////////////////
    // Update and Draw methods
    // /////////////////////////////////////////////////////////////////////////

    @Override
    public void update(ElapsedTime elapsedTime) {

        //process any touch events occurring since the update
        Input input = game.getInput();
        List<TouchEvent> touchEvents = input.getTouchEvents();

        if (touchEvents.size() > 0) {

            //Just check the first touch event that occurred in the frame.
            //It means pressing the screen with several fingers may not
            //trigger a 'button'.
            TouchEvent touchEvent = touchEvents.get(0);
            if (backButtonBound.contains((int) touchEvent.x, (int) touchEvent.y)
                    && touchEvent.type == TouchEvent.TOUCH_UP) {
                // If the play game area has been touched then swap screens
                game.getScreenManager().removeScreen(this.getName());
                MenuScreen menuScreen = new MenuScreen(game);
                if (Settings.soundEnabled) {
                    screenClickMusic.play();
                }
                // As it's the only added screen it will become active.
                game.getScreenManager().addScreen(menuScreen);
            } /*else if (hazardCardBound.contains((int) touchEvent.x, (int) touchEvent.y)
                    && touchEvent.type == TouchEvent.TOUCH_DOWN) {
                RelativeLayout.LayoutParams lparams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                _xDelta = X - lparams.leftMargin;
                _yDelta = Y - lparams.topMargin;

            }*/
        }
    }
    @Override
    public void draw(ElapsedTime elapsedTime, IGraphics2D graphics2D) {
    //  load hazard playing card
        /*ImageView hazardCardImageView = (ImageView) view.findViewById(R.id.hazardCardImageView);
        if (hazardCard != null) {
            hazardCardImageView.setImageBitmap(hazardCard);
        }

        cardImage1 = (ImageView) rootLayout.findViewById(R.id.hazardCardImageView);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(500, 150);
        cardImage1.setLayoutParams(layoutParams);
        cardImage1.setOnTouchListener(new ChoiceTouchListener());*/

        // Get and draw the bitmaps into the defined rectangles
        Bitmap backButton = game.getAssetManager().getBitmap("backButton");

        // Create the screen to black and define a clip based on the viewport
        graphics2D.clear(Color.BLACK);
        //graphics2D.clipRect(mScreenViewport.toRect());
        // Define the rects what will be used to 'hold' the images
        int spacingX = game.getScreenWidth() / 8;
        int spacingY = game.getScreenHeight() / 8;
        int padding = spacingY / 10;    //padding between each button
        int line = 1;   //each button is on a new 'line' (under each other)

        hazardCardBound = new Rect(spacingX, spacingY * 2 + padding, spacingX * 7, spacingY * 3);

        if (frontLayerBound == null) {
            frontLayerBound = new Rect(0, 0, graphics2D.getSurfaceWidth(),
                    graphics2D.getSurfaceHeight());
        }

        if (backButtonBound == null) {
            int left = 10;
            int bottom = (graphics2D.getSurfaceHeight() - 120);

            backButtonBound = new Rect(left, bottom, left + 100, bottom + 120);
        }

//添加了代码             cardImage1 =(ImageView)rootLayout.findViewById(R.id.hazardCardImageView);

        cardImage1.setLayoutParams(layoutParams);
        cardImage1.setOnTouchListener(new ChoiceTouchListener());
        cardImage1.setOnTouchListener(new ChoiceTouchListener());
        cardImage1.setImageBitmap(hazardCard);*/

        //draw bitmaps with relative bounds
        graphics2D.drawBitmap(backgroundBitmap, null, frontLayerBound,null);
        graphics2D.drawBitmap(backButton, null, backButtonBound, null);
        graphics2D.drawBitmap(hazardCard,null, hazardCardBound, null);


        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(500, 150);
        cardImage1.setLayoutParams(layoutParams);
        cardImage1.setImageBitmap(hazardCard);
        cardImage1.setOnTouchListener(new ChoiceTouchListener());

  }

    private final class ChoiceTouchListener implements View.OnTouchListener {
        public boolean onTouch(View view, MotionEvent event) {
            final int X = (int) event.getRawX();
            final int Y = (int) event.getRawY();
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    RelativeLayout.LayoutParams lparams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    _xDelta = X - lparams.leftMargin;
                    _yDelta = Y - lparams.topMargin;
                    break;
                case MotionEvent.ACTION_UP:
                    break;
                case MotionEvent.ACTION_POINTER_DOWN:
                    break;
                case MotionEvent.ACTION_POINTER_UP:
                    break;
                case MotionEvent.ACTION_MOVE:
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    layoutParams.leftMargin = X - _xDelta;
                    layoutParams.topMargin = Y - _yDelta;
                    layoutParams.rightMargin = 0b11111111111111111111111100000110;
                    layoutParams.bottomMargin = 0b11111111111111111111111100000110;
                    view.setLayoutParams(layoutParams);
                    break;
            }
            rootLayout.invalidate();
            return true;
        }
    }

编辑注意:我在代码行中添加了初始化imageView ..

编辑:主要活动类:

import android.app.Activity;
import android.app.FragmentManager;
import android.graphics.PointF;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.example.llave_000.shootout.world.DemoGame;
import android.view.GestureDetector;
import android.widget.ImageView;

public class MainActivity extends Activity implements View.OnTouchListener {

    private float mScaleFactor = 1.0f;
    private float mRotationDegrees = 0.f;
    private float mFocusX = 0.f;
    private float mFocusY = 0.f;
    private ImageView cardImage1;
    private ViewGroup rootLayout;



    /**
     * Game fragment instance
     */
    private Game mGame;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);


        cardImage1 = (ImageView) rootLayout.findViewById(R.id.hazardCardImageView);

        // Setup Gesture Detectors
        mScaleDetector = new ScaleGestureDetector(getApplicationContext(), new ScaleListener());
        /*mRotateDetector = new RotationGestureDetector(getApplicationContext(), new RotateListener());
        mMoveDetector = new MoveGestureDetector(getApplicationContext(), new MoveListener());*/


        // Setup the window as suitable for a game, namely: full screen
        // with no title and a request to keep the screen on. The changes
        // are made before any content is inflated.
        Window window = getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        // Set the content view to use a simple frame layout
        setContentView(R.layout.activity_main);

        // Add in the main game fragment..
        FragmentManager fm = getFragmentManager();
       // MenuScreen menuScreen = (MenuScreen)fm.findFragmentById(R.id.activity_main_id);
        mGame = (Game)fm.findFragmentById(R.id.activity_main_id);

        if (mGame == null) {
            mGame = new DemoGame(); //not sure if correct
            fm.beginTransaction().add(R.id.activity_main_id, mGame)
                    .commit();
        }


    }



    @Override
    public void onBackPressed() {
        // If the fragment does not consume the back event then
        // trigger the default behaviour
        if(!mGame.onBackPressed())
            super.onBackPressed();
    }

   /* public boolean onTouchEvent(MotionEvent me) {
        if (me.getAction() == MotionEvent.ACTION_DOWN) {
            //code in here to take me to new screen with match attax background
            //with new screen displaying a card. then work on being able to move that card.

            //playButtonY -= 20;

        }*/
       // playButton.setY(playButtonY);
        //code in here to take me to new screen with match attax background
        //with new screen displaying a card. then work on being able to move that card.

        //return true;
    }

新错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.llave_000.shootout/com.example.llave_000.shootout.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
    at com.example.llave_000.shootout.MainActivity.onCreate(MainActivity.java:42)
    at android.app.Activity.performCreate(Activity.java:6662)

编辑:: GameScreen类:

import com.example.llave_000.shootout.Game;
import com.example.llave_000.shootout.engine.ElapsedTime;
import com.example.llave_000.shootout.engine.graphics.IGraphics2D;
import com.example.llave_000.shootout.util.ILifeCycle;

/**
 * GameScreen - represents a type of Screen in the Game.
 * methods
 * 
 */
public abstract class GameScreen {

    /**
     * Name that is given to this game screen
     */
    protected final String name;

    /**
     * Return the name of this game screen
     * 
     * @return Name of this game screen
     */
    public String getName() {
        return name;
    }

    /**
     * Game to which game screen belongs
     */
    protected final Game game;

    /**
     * Return the game to which this game screen is attached
     * 
     * @return Game to which screen is attached
     */
    public Game getGame() {
        return game;
    }

    /**
     * Create a new game screen associated with the specified game instance
     * 
     * @param game
     *            Game instance to which the game screen belongs
     */
    public GameScreen(String name, Game game) {
        this.name = name;
        this.game = game;
    }

    /**
     * Update the game screen. Invoked automatically from the game.
     * 
     * NOTE: If the update is multi-threaded control should not be returned from
     * the update call until all update processes have completed.
     * 
     * @param elapsedTime
     *            Elapsed time information for the frame
     */
    public abstract void update(ElapsedTime elapsedTime);

    /**
     * Draw the game screen. Invoked automatically from the game.
     * 
     * @param elapsedTime
     *            Elapsed time information for the frame
     * @param graphics2D
     *            Graphics instance used to draw the screen
     */
    public abstract void draw(ElapsedTime elapsedTime, IGraphics2D graphics2D);

    /**
     * Invoked automatically by the game whenever the app is paused.
     */
    public void pause() {
    }
    /**
     * Invoked automatically by the game whenever the app is resumed.
     */
    public void resume() {
    }

    /**
     * Invoked automatically by the game whenever the app is disposed.
     */
    public void dispose() {
    }
}

1 个答案:

答案 0 :(得分:0)

您的cardImage1未初始化。您正在null imageview上设置布局参数。这就是它获得NullPointerException的原因。 如果它解决了您的问题,那么它会更好您的问题和错误日志。