连接在机器人2图像 [英] Connecting 2 images in android

查看:115
本文介绍了连接在机器人2图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要连接2图像的机器人。例如,

我想他们是这样的,

我已经通过硬编码做到了。首先,我觉得绿色图像的左上角,然后找到触摸事件的event.gerRawX()和event.getRawY()参数的最左下角点绿色side.I的做到这一点。现在我知道在x和y这两个点之间的距离。我做了类似的事情了红色的了。现在,当绿片移到靠近红我只是计算,如果左上点红一块是靠近绿一块的左下方。如果是的话我翻译绿色/红色到另一个。但是,这很难codeD计算应失败同样大小的平板电脑或手机,不同的分辨率。我只是想知道我怎么推广的解决方案。谢谢你。

编辑:我GameActivity和一流的imageinfo在我尝试连接两个图像。我反倒6图片。而我wanto将它们连接起来。像图像1将连接到图像2和图像2〜3,依此类推。

GameActivity类

 包com.example.JigSawPuzzle;


进口com.example.test.R;

进口android.annotation.Sup pressLint;
进口android.app.Activity;
进口android.app.AlertDialog;
进口android.app.Dialog;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.content.pm.ActivityInfo;
进口android.content.res.Configuration;
进口android.graphics.Point;
进口android.media.AudioManager;
进口android.media.SoundPool;
进口android.os.Bundle;
进口android.util.DisplayMetrics;
进口android.util.Log;
进口android.view.Display;
进口android.view.MotionEvent;
进口android.view.Surface;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.view.View.OnTouchListener;
进口android.view.ViewGroup.LayoutParams;

进口android.widget.Button;
进口android.widget.ImageView;
进口android.widget.RelativeLayout;
进口android.widget.Toast;

@燮pressLint(NewApi)
公共类GameActivity扩展活动实现OnTouchListener
{
静态双screenInches;
INT touchStartX = 0;
INT touchStartY = 0;

INT diffX = 0;
INT diffY = 0;
INT attachedPieces = 0;
INT IMAGEX = 0;
INT宜美= 0;
INT高度,宽度;
布尔[]标志为新的布尔[7];
布尔isPortait;
RelativeLayout的relataivelayoutLayout;
RelativeLayout.LayoutParams paramsA,paramsB,paramsC,paramsD,paramsE,paramsF;
ImageView的imageA,imageB,imageC,成像,imageE,imageF;
的imageinfo [] imageInfoArray =新的imageinfo [7];

//添加了音效
私人的Soundpool的Soundpool;
私人诠释correctPieceAttachSoundId,gameFinishSoundId;
私人布尔装= FALSE;

//为10寸景观高度= 752,宽度= 1280;纵向高度= 1232的宽度= 800

@覆盖
保护无效的onCreate(包savedInstanceState)
{
    super.onCreate(savedInstanceState);
    isPortait =(getResources()。getConfiguration()。方向== Configuration.ORIENTATION_LANDSCAPE)?假:真的;
    显示显示= getWindowManager()getDefaultDisplay()。
    身高= display.getHeight();
    宽度= display.getWidth();

    imageA =新ImageView的(这一点);
    imageB =新ImageView的(这一点);
    imageC =新ImageView的(这一点);
    成像=新ImageView的(这一点);
    imageE =新ImageView的(这一点);
    imageF =新ImageView的(这一点);

    DisplayMetrics DM =新DisplayMetrics();
    。getWindowManager()getDefaultDisplay()getMetrics(DM)。
    双X = Math.pow(dm.widthPixels / dm.xdpi,2);
    双Y = Math.pow(dm.heightPixels / dm.ydpi,2);
    screenInches =的Math.sqrt(X + Y);


    如果(screenInches> 9.0)
    {

        imageA.setBackgroundResource(R.drawable.a);
        imageB.setBackgroundResource(R.drawable.b);
        imageC.setBackgroundResource(R.drawable.c);
        imageD.setBackgroundResource(R.drawable.d);
        imageE.setBackgroundResource(R.drawable.e);
        imageF.setBackgroundResource(R.drawable.f);
    }
    其他
    {
        imageA.setBackgroundResource(R.drawable.aa);
        imageB.setBackgroundResource(R.drawable.bb);
        imageC.setBackgroundResource(R.drawable.cc);
        imageD.setBackgroundResource(R.drawable.dd);
        imageE.setBackgroundResource(R.drawable.ee);
        imageF.setBackgroundResource(R.drawable.ff);
    }



    imageA.setId(1);
    imageA.setTag(一);
    paramsA =新RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //该WRAP_CONTENT参数可以由一个绝对的宽度和高度或FILL_PARENT选项代替)
    imageA.setLayoutParams(paramsA);
    imageA.setOnTouchListener(本);
    //Log.d("GameActivity,)



    imageB.setId(2);
    imageB.setTag(B);
    paramsB =新RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //该WRAP_CONTENT参数可以由一个绝对的宽度和高度或FILL_PARENT选项代替)
    imageB.setLayoutParams(paramsB);
    imageB.setOnTouchListener(本);



    imageC.setId(3);
    imageC.setTag(C);
    paramsC =新RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //该WRAP_CONTENT参数可以由一个绝对的宽度和高度或FILL_PARENT选项代替)
    imageC.setLayoutParams(paramsC);
    imageC.setOnTouchListener(本);


    imageD.setId(4);
    imageD.setTag(D);
    paramsD =新RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //该WRAP_CONTENT参数可以由一个绝对的宽度和高度或FILL_PARENT选项代替)
    imageD.setLayoutParams(paramsD);
    imageD.setOnTouchListener(本);


    imageE.setId(5);
    imageE.setTag(E);
    paramsE =新RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //该WRAP_CONTENT参数可以由一个绝对的宽度和高度或FILL_PARENT选项代替)
    imageE.setLayoutParams(paramsE);
    imageE.setOnTouchListener(本);

    imageF.setId(6);
    imageF.setTag(F);
    paramsF =新RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //该WRAP_CONTENT参数可以由一个绝对的宽度和高度或FILL_PARENT选项代替)
    imageF.setLayoutParams(paramsF);
    imageF.setOnTouchListener(本);
    setupPieces();


    //设置硬件按钮来控制音乐
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    //将声音
    的Soundpool =新的Soundpool(10,AudioManager.STREAM_MUSIC,0);
    soundPool.setOnLoadCompleteListener(新SoundPool.OnLoadCompleteListener()
    {
        @覆盖
        公共无效的onLoadComplete(的Soundpool的Soundpool,诠释sampleId,诠释状态){

            加载=真正的;
        }
    });

    gameFinishSoundId = soundPool.load(此,R.raw.bells,1);
    correctPieceAttachSoundId = soundPool.load(此,R.raw.bell,1);

}

公共无效playSound(INT soundId)
{
    AudioManager audioManager =(AudioManager)getSystemService(AUDIO_SERVICE);
    浮动actualVolume =(浮点)audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    浮动maxVolume =(浮点)audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    浮动量= actualVolume / maxVolume;
    //声音是已经加载?
    如果(装入)
    {
        soundPool.play(soundId,体积,容量,1,0,1.0F);
    }
}

公共无效onConfigurationChanged(配置NEWCONFIG)
{
    super.onConfigurationChanged(NEWCONFIG);

    //检查屏幕的方向
    如果(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
    {
// Toast.makeText(这一点,风景,Toast.LENGTH_SHORT).show();
    }
    否则,如果(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
    {
// Toast.makeText(这一点,肖像,Toast.LENGTH_SHORT).show();
    }
 // Toast.makeText(这一点,在OnConfiguaration更改,Toast.LENGTH_SHORT).show();
    isPortait =(getResources()。getConfiguration()。方向== Configuration.ORIENTATION_LANDSCAPE)?假:真的;
    ((RelativeLayout的)imageA.getParent())removeAllViews()。
    Log.d(在onconfigurationChangedGameActivity);
    setupPieces();
}
公共无效setupPieces()
{
    RelativeLayout的relataivelayoutLayout =新RelativeLayout的(这一点);
    显示显示= getWindowManager()getDefaultDisplay()。
    身高= display.getHeight();
    宽度= display.getWidth();



    如果(!isPortait)
    {
        paramsA.leftMargin = 10; //你的X坐标
        paramsA.topMargin = 30; //你的Y坐标
    }
    其他
    {
        paramsA.leftMargin = 30; //你的X坐标
        paramsA.topMargin = 10; //你的Y坐标
    }


    imageA.setLayoutParams(paramsA);
    imageA.setOnTouchListener(本);
    //Log.d("GameActivity,)


    如果(!isPortait)
    {
        paramsB.leftMargin = 650; //你的X坐标
        paramsB.topMargin = 300; //你的Y坐标
    }
    其他
    {
        paramsB.leftMargin = 300; //你的X坐标
        paramsB.topMargin = 750; //你的Y坐标
    }
    imageB.setLayoutParams(paramsB);
    imageB.setOnTouchListener(本);


    如果(!isPortait)
    {
        paramsC.leftMargin = 400; //你的X坐标
        paramsC.topMargin = 380; //你的Y坐标
    }
    其他
    {
        paramsC.leftMargin = 400; //你的X坐标
        paramsC.topMargin = 350; //你的Y坐标
    }
    imageC.setLayoutParams(paramsC);
    imageC.setOnTouchListener(本);


    如果(!isPortait)
    {
        paramsD.leftMargin = 750; //你的X坐标
        paramsD.topMargin = 20; //你的Y坐标
    }
    其他
    {
        paramsD.leftMargin = 20; //你的X坐标
        paramsD.topMargin = 750; //你的Y坐标
    }
    imageD.setLayoutParams(paramsD);
    imageD.setOnTouchListener(本);


    如果(!isPortait)
    {
        paramsE.leftMargin = 900; //你的X坐标
        paramsE.topMargin = 400; //你的Y坐标
    }
    其他
    {
        paramsE.leftMargin = 475; //你的X坐标
        paramsE.topMargin = 700; //你的Y坐标
    }
    imageE.setLayoutParams(paramsE);
    imageE.setOnTouchListener(本);


    如果(!isPortait)
    {
        paramsF.leftMargin = 90; //你的X坐标
        paramsF.topMargin = 300; //你的Y坐标
    }
    其他
    {
        paramsF.leftMargin = 90; //你的X坐标
        paramsF.topMargin = 300; //你的Y坐标
    }
    imageF.setLayoutParams(paramsF);
    imageF.setOnTouchListener(本);
    的imageinfo imageAinfo =新的imageinfo(imageA.getId(),imageA,1,2);
    imageInfoArray [0] = imageAinfo;
    的imageinfo imageBinfo =新的imageinfo(imageB.getId(),imageB,1,3);
    imageInfoArray [1] = imageBinfo;
    的imageinfo imageCinfo =新的imageinfo(imageC.getId(),imageC,2,4);
    imageInfoArray [2] = imageCinfo;
    的imageinfo imageDinfo =新的imageinfo(imageD.getId(),成像,3,5);
    imageInfoArray [3] = imageDinfo;
    的imageinfo imageEinfo =新的imageinfo(imageE.getId(),imageE,4,6);
    imageInfoArray [4] = imageEinfo;
    的imageinfo imageFinfo =新的imageinfo(imageF.getId(),imageF,5,6);
    imageInfoArray [5] = imageFinfo;



    relataivelayoutLayout.addView(imageA);
    relataivelayoutLayout.addView(imageB);
    relataivelayoutLayout.addView(imageC);
    relataivelayoutLayout.addView(摄像);
    relataivelayoutLayout.addView(imageE);
    relataivelayoutLayout.addView(imageF);


    的setContentView(relataivelayoutLayout);


}
私人无效updatePosition(INT ID)
{
    如果(旗[imageInfoArray [ID-1] .ID])
        返回;
    标志[imageInfoArray [ID-1] .ID] = TRUE;

    RelativeLayout.LayoutParams参数=(RelativeLayout.LayoutParams)imageInfoArray [ID-1] .imageView.getLayoutParams();
    param.leftMargin = imageInfoArray [ID-1] .imageView.getLeft()+ diffX;
    param.topMargin = imageInfoArray [ID-1] .imageView.getTop()+ diffY;
    imageInfoArray [ID-1] .imageView.setLayoutParams(参数);
    如果(imageInfoArray [ID-1] .isTopConnected)
        updatePosition(imageInfoArray [ID-1] .topPieceId);
    如果(imageInfoArray [ID-1] .isBottomConnected)
        updatePosition(imageInfoArray [ID-1] .bottomPieceId);
    返回;
}
@覆盖
公共布尔onTouch(视图V,MotionEvent事件)
{

    如果(V的instanceof ImageView的)
    {

        ImageView的ImageView的=(ImageView的)V;
        的imageinfo的imageinfo = imageInfoArray [imageView.getId() -  1];

        开关(event.getAction()及MotionEvent.ACTION_MASK)
        {

            案例MotionEvent.ACTION_DOWN:

                touchStartX =(int)的event.getRawX();
                touchStartY =(int)的event.getRawY();
                IMAGEX = imageView.getLeft();
                宜美= imageView.getTop();
                //Toast.makeText(this,×=+ event.getRawX()+Y =+ event.getRawY(),Toast.LENGTH_SHORT).show();
                打破;

            案例MotionEvent.ACTION_UP:

                touchStartX =(int)的event.getRawX();
                touchStartY =(int)的event.getRawY();
                IMAGEX = imageView.getLeft();
                宜美= imageView.getTop();
                INT ID = imageInfo.id;
                而(imageInfo.isTopConnected)
                {
                    如果(imageInfo.id == imageInfo.topPieceId)
                        打破;
                    的imageinfo = imageInfoArray [imageInfo.topPieceId-1];
                }
                如果(!imageInfo.isTopConnected)
                {
                    ImageView的= imageInfo.imageView;
                    INT topConnectingPieceId = imageInfo.topPieceId;
                    INT topConnectingX = 0,topConnectingY = 0;
                    topConnectingX = imageInfo.calculateTopX(imageView.getLeft(),imageView.getId());
                    topConnectingY = imageInfo.calculateTopY(imageView.getTop(),imageView.getId());


                    的imageinfo topImageInfo = imageInfoArray [topConnectingPieceId-1];
                    INT bottomConnectingX = topImageInfo.calculateBottomX(topImageInfo.imageView.getLeft(),topConnectingPieceId);
                    INT bottomConnectingY = topImageInfo.calculateBottomY(topImageInfo.imageView.getTop(),topConnectingPieceId);
                    diffX =(bottomConnectingX-topConnectingX);
                    diffY =(bottomConnectingY-topConnectingY);
                    如果(Math.abs(diffX)其中; = 20&安培;&安培; Math.abs(diffY)其中; = 20)
                    {
                        的for(int i = 0;我7;;我++)
                            标志[我] = FALSE;
                        updatePosition(imageInfo.id);
                        imageInfo.setIsTopConnected(真正的);
                        topImageInfo.setIsBottomConnected(真正的);
                        attachedPieces ++;
                        如果(attachedPieces == 5)
                        {
                            setupFinishDialogue();
                            playSound(gameFinishSoundId);
                        }
                        其他
                            playSound(correctPieceAttachSoundId);
                        打破;
                    }
                }
                的imageinfo = imageInfoArray [ID-1];
                而(imageInfo.isBottomConnected)
                {
                    如果(imageInfo.id == imageInfoArray [imageInfo.bottomPieceId-1] .ID)
                        打破;
                    的imageinfo = imageInfoArray [imageInfo.bottomPieceId-1];
                }
                ImageView的= imageInfo.imageView;
                如果(!imageInfo.isBottomConnected)
                {
                    INT topConnectingX = 0,topConnectingY = 0;
                    INT bottomConnectingX = imageInfo.calculateBottomX(imageView.getLeft(),imageView.getId());
                    INT bottomConnectingY = imageInfo.calculateBottomY(imageView.getTop(),imageView.getId());
                    INT bottomConnectingPieceId = imageInfo.bottomPieceId;
                    的imageinfo bottomImageInfo = imageInfoArray [bottomConnectingPieceId-1];
                    topConnectingX = bottomImageInfo.calculateTopX(bottomImageInfo.imageView.getLeft(),bottomConnectingPieceId);
                    topConnectingY = bottomImageInfo.calculateTopY(bottomImageInfo.imageView.getTop(),bottomConnectingPieceId);
                    diffX =(topConnectingX-bottomConnectingX);
                    diffY =(topConnectingY-bottomConnectingY);
                    如果(Math.abs(diffX)其中; = 20&安培;&安培; Math.abs(diffY)其中; = 20)
                    {
                        的for(int i = 0;我7;;我++)
                            标志[我] = FALSE;
                        updatePosition(imageInfo.id);
                        imageInfo.setIsBottomConnected(真正的);
                        bottomImageInfo.setIsTopConnected(真正的);
                        attachedPieces ++;
                        如果(attachedPieces == 5)
                        {
                            setupFinishDialogue();
                            playSound(gameFinishSoundId);
                        }
                        其他
                            playSound(correctPieceAttachSoundId);
                    }
                }

                打破;

            案例MotionEvent.ACTION_MOVE:

                diffX =(int)的(event.getRawX() -  touchStartX);
                diffY =(int)的(event.getRawY() -  touchStartY);
                touchStartX =(int)的event.getRawX();
                touchStartY =(int)的event.getRawY();

                的for(int i = 0;我7;;我++)
                    标志[我] = FALSE;
                updatePosition(imageInfo.id);
                打破;

            默认:
                打破;
        }

    }

    返回true;
}

无效lockOrientation()
{
    开关(getResources()。getConfiguration()。方向)
    {
        案例Configuration.ORIENTATION_PORTRAIT:
            如果(android.os.Build.VERSION.SDK_INT< android.os.Build.VERSION_ codeS.FROYO)
            {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            其他
            {
                INT旋转= getWindowManager()getDefaultDisplay()getRotation()。
                如果(旋转== android.view.Surface.ROTATION_90 ||旋转== android.view.Surface.ROTATION_180)
                {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
                }
                其他
                {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            }
            打破;

        案例Configuration.ORIENTATION_LANDSCAPE:
            如果(android.os.Build.VERSION.SDK_INT< android.os.Build.VERSION_ codeS.FROYO)
            {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
            其他
            {
                INT旋转= getWindowManager()getDefaultDisplay()getRotation()。
                如果(旋转== android.view.Surface.ROTATION_0 ||旋转== android.view.Surface.ROTATION_90){
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
                其他
                {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
                }
            }
            打破;
    }
}

无效setupFinishDialogue()
{
    /*if(getWindowManager().getDefaultDisplay().getRotation()==3)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    否则如果(getWindowManager()。getDefaultDisplay()。getRotation()== 1)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
    否则如果(getWindowManager()。getDefaultDisplay()。getRotation()== 2)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
    其他setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); * /


    lockOrientation();

    AlertDialog.Builder builderForAlertBox =新AlertDialog.Builder(本);
    builderForAlertBox.setCancelable(假).setMessage(干得好!)。setPositiveButton(重新启动,dialogClickListner).setNegativeButton(退出,dialogClickListner)。
    setCancelable(真).show();
}
DialogInterface.OnClickListener dialogClickListner =新DialogInterface.OnClickListener()
{
    公共无效的onClick(DialogInterface对话,诠释其)
    {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        切换(这){
        案例DialogInterface.BUTTON_POSITIVE:
            完();
            意向意图=新的意图(getApplicationContext(),GameActivity.class);
            startActivity(意向);
            打破;

        案例DialogInterface.BUTTON_NEGATIVE:
            完();
        默认:
            打破;
        }

    }
};
 

}

的imageinfo类

 包com.example.JigSawPuzzle;

进口android.widget.ImageView;
进口android.widget.Toast;

公共类的imageinfo
{
ImageView的ImageView的;
INT imageATopLeftDifferenceX = -1;
INT imageATopLeftDifferenceY = -1;
INT imageABottomRightDifferenceX = 113;
INT imageABottomRightDifferenceY = 140;

INT imageBTopLeftDifferenceX = 0;
INT imageBTopLeftDifferenceY = 0;
INT imageBBottomRightDifferenceX = 0;
INT imageBBottomRightDifferenceY = 111;

INT imageCTopLeftDifferenceX = 14;
INT imageCTopLeftDifferenceY = 0;
INT imageCBottomRightDifferenceX = 0;
INT imageCBottomRightDifferenceY = 88;

INT imageDTopLeftDifferenceX = 92;
INT imageDTopLeftDifferenceY = 2;
INT imageDBottomRightDifferenceX = 0;
INT imageDBottomRightDifferenceY = 70;

/ * INT imageETopLeftDifferenceX = 0;
INT imageETopLeftDifferenceY = 0;
INT imageEBottomRightDifferenceX = 55;
INT imageEBottomRightDifferenceY = 112; * /
INT imageETopLeftDifferenceX = 55;
INT imageETopLeftDifferenceY = 112;
INT imageEBottomRightDifferenceX = 0;
INT imageEBottomRightDifferenceY = 0;

/ * INT imageFTopLeftDifferenceX = 0;
INT imageFTopLeftDifferenceY = 26;
INT imageFBottomRightDifferenceX = 0;
INT imageFBottomRightDifferenceY = 109;
INT ID,topPieceId,bottomPieceId; * /
INT imageFTopLeftDifferenceX = 0;
INT imageFTopLeftDifferenceY = 109;
INT imageFBottomRightDifferenceX = 0;
INT imageFBottomRightDifferenceY = 26;
INT ID,topPieceId,bottomPieceId;

布尔isTopConnected = FALSE;
布尔isBottomConnected = FALSE;
公众的imageinfo(INT ID,ImageView的ImageView的,INT topPieceId,INT bottomPieceId)
{
    this.topPieceId = topPieceId;
    this.bottomPieceId = bottomPieceId;
    this.imageView = ImageView的;
    this.id = ID;
    如果(ID == 1)
        isTopConnected = TRUE;
    否则,如果(ID == 6)
        isBottomConnected = TRUE;
    如果(GameActivity.screenInches> 9.0)
        initializePiecesInfo();
}
私人无效initializePiecesInfo()
{

    imageATopLeftDifferenceX = 0;
    imageATopLeftDifferenceY = 0;
    imageABottomRightDifferenceX = 150;
    imageABottomRightDifferenceY = 184;

    imageBTopLeftDifferenceX = 0;
    imageBTopLeftDifferenceY = 0;
    imageBBottomRightDifferenceX = 0;
    imageBBottomRightDifferenceY = 148;

    imageCTopLeftDifferenceX = 23;
    imageCTopLeftDifferenceY = 0;
    imageCBottomRightDifferenceX = 0;
    imageCBottomRightDifferenceY = 115;

    imageDTopLeftDifferenceX = 121;
    imageDTopLeftDifferenceY = 0;
    imageDBottomRightDifferenceX = 0;
    imageDBottomRightDifferenceY = 91;

    / * INT imageETopLeftDifferenceX = 0;
    INT imageETopLeftDifferenceY = 0;
    INT imageEBottomRightDifferenceX = 55;
    INT imageEBottomRightDifferenceY = 112; * /
    imageETopLeftDifferenceX = 74;
    imageETopLeftDifferenceY = 147;
    imageEBottomRightDifferenceX = 0;
    imageEBottomRightDifferenceY = 0;

    / * INT imageFTopLeftDifferenceX = 0;
    INT imageFTopLeftDifferenceY = 26;
    INT imageFBottomRightDifferenceX = 0;
    INT imageFBottomRightDifferenceY = 109;
    INT ID,topPieceId,bottomPieceId; * /
    imageFTopLeftDifferenceX = 0;
    imageFTopLeftDifferenceY = 144;
    imageFBottomRightDifferenceX = 0;
    imageFBottomRightDifferenceY = 26;
}

INT calculateTopX(INT realX,INT ID)
{
    如果(ID == 2)
        返回realX + imageBTopLeftDifferenceX;
    如果(ID == 3)
        返回realX + imageCTopLeftDifferenceX;
    如果(ID == 4)
        返回realX + imageDTopLeftDifferenceX;
    如果(ID == 5)
        返回realX + imageETopLeftDifferenceX;
    如果(ID == 6)
        返回realX + imageFTopLeftDifferenceX;
    返回realX;

}
INT calculateTopY(INT真的,INT ID)
{
    如果(ID == 2)
        返回真的+ imageBTopLeftDifferenceY;
    如果(ID == 3)
        返回真的+ imageCTopLeftDifferenceY;
    如果(ID == 4)
        返回真的+ imageDTopLeftDifferenceY;
    如果(ID == 5)
        返回真的+ imageETopLeftDifferenceY;
    如果(ID == 6)
        返回真的+ imageFTopLeftDifferenceY;
    返回真的;
}

INT calculateBottomX(INT realX,INT ID)
{
    如果(ID == 1)
        返回realX + imageABottomRightDifferenceX;
    如果(ID == 2)
        返回realX + imageBBottomRightDifferenceX;
    如果(ID == 3)
        返回realX + imageCBottomRightDifferenceX;
    如果(ID == 4)
        返回realX + imageDBottomRightDifferenceX;
    如果(ID == 5)
        返回realX + imageEBottomRightDifferenceX;
    返回realX + imageFBottomRightDifferenceX;
}
INT calculateBottomY(INT真的,INT ID)
{
    如果(ID == 1)
        返回真的+ imageABottomRightDifferenceY;
    如果(ID == 2)
        返回真的+ imageBBottomRightDifferenceY;
    如果(ID == 3)
        返回真的+ imageCBottomRightDifferenceY;
    如果(ID == 4)
        返回真的+ imageDBottomRightDifferenceY;
    如果(ID == 5)
        返回真的+ imageEBottomRightDifferenceY;
    返回真的+ imageFBottomRightDifferenceY;
}
无效setIsTopConnected(布尔isTopConnected)
{
    this.isTopConnected = isTopConnected;
}
无效setIsBottomConnected(布尔isBottomConnected)
{
    this.isBottomConnected = isBottomConnected;
}

}
 

解决方案

给你提供的是简单的将它们连接在一个通用的方法,因为图像的宽度相同,他们有透明背景的图像,这里的理念是:

1,您需要两个图像,你可以从底部或顶部图像

计算之间的重叠距离

在底部的图片绿线应等于红线在顶部图像

由于图像具有透明背景,你可以很容易地计算出这个距离,我将在这里使用的底层图像。

我们的想法是要检查每一个像素在底部的位图的最后一列(即宽度 - 1),并停止一旦你打一个非透明像素

 私人诠释getOverlapDistance(位图bottomBitmap){
    INT高= bottomBitmap.getHeight();
    INT宽度= bottomBitmap.getWidth();
    INT距离= 0;
    的for(int i = 0; I<高度;我++){
        如果(Color.alpha(bottomBitmap.getPixel(宽度 -  1,i))的= 0){
            距离=第(i + 1);
            打破;
        }
    }
    返回的距离;
}
 

要连接它们,你可以这样做(假设你有单独的的ImageView 的顶部和底部图像):

 位=((BitmapDrawable)bottomImage.getDrawable())getBitmap()。
INT overlapDistance = getOverlapDistance(位);
bottomImage.setTop(topImage.getBottom() -  overlapDistance);
 

其实我想这有一个简单的活动,它是工作,在这里是如何看起来像前,连接两个影像后:

我只是执行上面的code当按钮连接点击

I want to connect 2 images in android. Example,

I want them to be like this,

I have already done it by hard coding. First I find the upper left of the green image and then find the the most lower left point of the green side.I do it with touch event's event.gerRawX() and event.getRawY() parameters. Now I know the distance in x and y between those two points. I do the similar thing for the red one too. Now when green piece is moved close to the red I just calculate if upper left point of red piece is near to the lower left of the green piece. if so I translate the green one/ red one to the other one. But this hard coded calculation should fail for same size tablet or phone with different resolution. I just want to know how do I generalize the solution. Thanks.

Edit: My GameActivity and ImageInfo class where I try to connect both images. I have actually 6 images like this. And i wanto connect them. Like image 1 will connect to image 2 and image 2 to 3 and so on.

GameActivity class

package com.example.JigSawPuzzle;


import com.example.test.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;    
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Point;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

@SuppressLint("NewApi")
public class GameActivity extends Activity implements OnTouchListener
{
static double screenInches;
int touchStartX = 0;
int touchStartY = 0;

int diffX = 0;
int diffY = 0;
int attachedPieces=0;
int imageX = 0;
int imageY = 0;
int height,width;
boolean [] flag = new boolean[7];
boolean isPortait;
RelativeLayout relataivelayoutLayout;
RelativeLayout.LayoutParams paramsA,paramsB,paramsC,paramsD,paramsE,paramsF;
ImageView imageA,imageB,imageC,imageD,imageE,imageF;
ImageInfo [] imageInfoArray = new ImageInfo[7];

// added for sound effect
private SoundPool soundPool;
private int correctPieceAttachSoundId,gameFinishSoundId;
private boolean loaded = false;

//for 10inch landscape height = 752, width = 1280; portrait height = 1232 width = 800

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    isPortait = (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) ?  false : true;
    Display display = getWindowManager().getDefaultDisplay();
    height = display.getHeight();
    width = display.getWidth();     

    imageA = new ImageView(this);
    imageB = new ImageView(this);
    imageC = new ImageView(this);
    imageD = new ImageView(this);
    imageE = new ImageView(this);
    imageF = new ImageView(this);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(dm.widthPixels/dm.xdpi,2);
    double y = Math.pow(dm.heightPixels/dm.ydpi,2);
    screenInches = Math.sqrt(x+y);


    if(screenInches>9.0)
    {

        imageA.setBackgroundResource(R.drawable.a); 
        imageB.setBackgroundResource(R.drawable.b);
        imageC.setBackgroundResource(R.drawable.c);
        imageD.setBackgroundResource(R.drawable.d);
        imageE.setBackgroundResource(R.drawable.e);
        imageF.setBackgroundResource(R.drawable.f);
    }
    else
    {
        imageA.setBackgroundResource(R.drawable.aa);    
        imageB.setBackgroundResource(R.drawable.bb);
        imageC.setBackgroundResource(R.drawable.cc);
        imageD.setBackgroundResource(R.drawable.dd);
        imageE.setBackgroundResource(R.drawable.ee);
        imageF.setBackgroundResource(R.drawable.ff);
    }



    imageA.setId(1);
    imageA.setTag("a");
    paramsA = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)                
    imageA.setLayoutParams(paramsA);
    imageA.setOnTouchListener(this);
    //Log.d("GameActivity", "")



    imageB.setId(2);
    imageB.setTag("b");
    paramsB = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
    imageB.setLayoutParams(paramsB);
    imageB.setOnTouchListener(this);



    imageC.setId(3);
    imageC.setTag("c");
    paramsC = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
    imageC.setLayoutParams(paramsC);
    imageC.setOnTouchListener(this);


    imageD.setId(4);
    imageD.setTag("d");
    paramsD = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
    imageD.setLayoutParams(paramsD);
    imageD.setOnTouchListener(this);


    imageE.setId(5);
    imageE.setTag("e");
    paramsE = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
    imageE.setLayoutParams(paramsE);
    imageE.setOnTouchListener(this);

    imageF.setId(6);
    imageF.setTag("f");
    paramsF = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
    imageF.setLayoutParams(paramsF);
    imageF.setOnTouchListener(this);
    setupPieces();


    // Set the hardware buttons to control the music
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    // Load the sound
    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener()
    {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {

            loaded = true;
        }
    });

    gameFinishSoundId = soundPool.load(this, R.raw.bells, 1);
    correctPieceAttachSoundId= soundPool.load(this, R.raw.bell, 1);

}

public void playSound(int soundId)
{
    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    float volume = actualVolume / maxVolume;
    // Is the sound loaded already?
    if (loaded) 
    {
        soundPool.play(soundId, volume, volume, 1, 0, 1.0f);
    }
}

public void onConfigurationChanged(Configuration newConfig) 
{
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) 
    {
//        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    }
    else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
    {
//        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
 //   Toast.makeText(this, "in OnConfiguaration Changed", Toast.LENGTH_SHORT).show();
    isPortait = (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) ?  false : true;
    ((RelativeLayout)imageA.getParent()).removeAllViews();
    Log.d("GameActivity", "in onconfigurationChanged");
    setupPieces();
}
public void setupPieces()
{
    RelativeLayout relataivelayoutLayout = new RelativeLayout(this);
    Display display = getWindowManager().getDefaultDisplay();
    height = display.getHeight();
    width = display.getWidth();



    if(!isPortait)
    {
        paramsA.leftMargin = 10; //Your X coordinate
        paramsA.topMargin = 30; //Your Y coordinate
    }
    else
    {
        paramsA.leftMargin = 30; //Your X coordinate
        paramsA.topMargin = 10; //Your Y coordinate
    }


    imageA.setLayoutParams(paramsA);
    imageA.setOnTouchListener(this);
    //Log.d("GameActivity", "")


    if(!isPortait)
    {
        paramsB.leftMargin = 650; //Your X coordinate
        paramsB.topMargin = 300; //Your Y coordinate
    }
    else
    {
        paramsB.leftMargin = 300; //Your X coordinate
        paramsB.topMargin = 750; //Your Y coordinate
    }
    imageB.setLayoutParams(paramsB);
    imageB.setOnTouchListener(this);


    if(!isPortait)
    {
        paramsC.leftMargin = 400; //Your X coordinate
        paramsC.topMargin = 380; //Your Y coordinate
    }
    else
    {
        paramsC.leftMargin = 400; //Your X coordinate
        paramsC.topMargin = 350; //Your Y coordinate
    }
    imageC.setLayoutParams(paramsC);
    imageC.setOnTouchListener(this);


    if(!isPortait)
    {
        paramsD.leftMargin = 750; //Your X coordinate
        paramsD.topMargin = 20; //Your Y coordinate
    }
    else
    {
        paramsD.leftMargin = 20; //Your X coordinate
        paramsD.topMargin = 750; //Your Y coordinate
    }
    imageD.setLayoutParams(paramsD);
    imageD.setOnTouchListener(this);


    if(!isPortait)
    {
        paramsE.leftMargin = 900; //Your X coordinate
        paramsE.topMargin = 400; //Your Y coordinate
    }
    else
    {
        paramsE.leftMargin = 475; //Your X coordinate
        paramsE.topMargin = 700; //Your Y coordinate
    }
    imageE.setLayoutParams(paramsE);
    imageE.setOnTouchListener(this);


    if(!isPortait)
    {
        paramsF.leftMargin = 90; //Your X coordinate
        paramsF.topMargin = 300; //Your Y coordinate
    }
    else
    {
        paramsF.leftMargin = 90; //Your X coordinate
        paramsF.topMargin = 300; //Your Y coordinate
    }
    imageF.setLayoutParams(paramsF);
    imageF.setOnTouchListener(this);
    ImageInfo imageAinfo = new ImageInfo(imageA.getId(),imageA,1,2);
    imageInfoArray[0] = imageAinfo;
    ImageInfo imageBinfo = new ImageInfo(imageB.getId(),imageB,1,3);
    imageInfoArray[1] = imageBinfo;
    ImageInfo imageCinfo = new ImageInfo(imageC.getId(),imageC,2,4);
    imageInfoArray[2] = imageCinfo;
    ImageInfo imageDinfo = new ImageInfo(imageD.getId(),imageD,3,5);
    imageInfoArray[3] = imageDinfo;
    ImageInfo imageEinfo = new ImageInfo(imageE.getId(),imageE,4,6);
    imageInfoArray[4] = imageEinfo;
    ImageInfo imageFinfo = new ImageInfo(imageF.getId(),imageF,5,6);
    imageInfoArray[5] = imageFinfo;



    relataivelayoutLayout.addView(imageA);
    relataivelayoutLayout.addView(imageB);
    relataivelayoutLayout.addView(imageC);
    relataivelayoutLayout.addView(imageD);
    relataivelayoutLayout.addView(imageE);
    relataivelayoutLayout.addView(imageF);


    setContentView(relataivelayoutLayout);


}
private void updatePosition(int id)
{
    if(flag[imageInfoArray[id-1].id])
        return;
    flag[imageInfoArray[id-1].id] = true;

    RelativeLayout.LayoutParams param = (RelativeLayout.LayoutParams)imageInfoArray[id-1].imageView.getLayoutParams();
    param.leftMargin = imageInfoArray[id-1].imageView.getLeft() + diffX;
    param.topMargin  = imageInfoArray[id-1].imageView.getTop() + diffY;
    imageInfoArray[id-1].imageView.setLayoutParams(param);
    if(imageInfoArray[id-1].isTopConnected)
        updatePosition(imageInfoArray[id-1].topPieceId);
    if(imageInfoArray[id-1].isBottomConnected)
        updatePosition(imageInfoArray[id-1].bottomPieceId);
    return;
}
@Override
public boolean onTouch(View v, MotionEvent event) 
{

    if(v instanceof ImageView)
    {

        ImageView imageView = (ImageView) v;
        ImageInfo imageInfo = imageInfoArray[imageView.getId()-1];

        switch (event.getAction() & MotionEvent.ACTION_MASK) 
        {

            case MotionEvent.ACTION_DOWN:

                touchStartX = (int) event.getRawX();
                touchStartY = (int) event.getRawY();
                imageX = imageView.getLeft();
                imageY = imageView.getTop();
                //Toast.makeText(this, "x = "+event.getRawX()+" y = "+event.getRawY(), Toast.LENGTH_SHORT).show();
                break;

            case MotionEvent.ACTION_UP:

                touchStartX = (int) event.getRawX();
                touchStartY = (int) event.getRawY();
                imageX = imageView.getLeft();
                imageY = imageView.getTop();
                int id = imageInfo.id;
                while(imageInfo.isTopConnected)
                {
                    if(imageInfo.id == imageInfo.topPieceId)
                        break;
                    imageInfo = imageInfoArray[imageInfo.topPieceId-1];                     
                }
                if(!imageInfo.isTopConnected)
                {
                    imageView = imageInfo.imageView;
                    int topConnectingPieceId = imageInfo.topPieceId;
                    int topConnectingX=0,topConnectingY=0;
                    topConnectingX = imageInfo.calculateTopX(imageView.getLeft(), imageView.getId());
                    topConnectingY = imageInfo.calculateTopY(imageView.getTop(), imageView.getId());


                    ImageInfo topImageInfo = imageInfoArray[topConnectingPieceId-1];
                    int bottomConnectingX = topImageInfo.calculateBottomX(topImageInfo.imageView.getLeft(),topConnectingPieceId);
                    int bottomConnectingY = topImageInfo.calculateBottomY(topImageInfo.imageView.getTop(),topConnectingPieceId);
                    diffX = (bottomConnectingX-topConnectingX);
                    diffY = (bottomConnectingY-topConnectingY);
                    if(Math.abs(diffX)<=20 && Math.abs(diffY)<=20)
                    {
                        for(int i=0;i<7;i++)
                            flag[i]=false;
                        updatePosition(imageInfo.id);
                        imageInfo.setIsTopConnected(true);
                        topImageInfo.setIsBottomConnected(true);
                        attachedPieces++;
                        if(attachedPieces==5)
                        {
                            setupFinishDialogue();
                            playSound(gameFinishSoundId);
                        }
                        else
                            playSound(correctPieceAttachSoundId);
                        break;
                    }
                }
                imageInfo = imageInfoArray[id-1];
                while(imageInfo.isBottomConnected)
                {
                    if(imageInfo.id == imageInfoArray[imageInfo.bottomPieceId-1].id)
                        break;
                    imageInfo = imageInfoArray[imageInfo.bottomPieceId-1];                      
                }
                imageView = imageInfo.imageView;
                if(!imageInfo.isBottomConnected)
                {
                    int topConnectingX=0,topConnectingY=0; 
                    int bottomConnectingX = imageInfo.calculateBottomX(imageView.getLeft(), imageView.getId());
                    int bottomConnectingY = imageInfo.calculateBottomY(imageView.getTop(), imageView.getId());
                    int bottomConnectingPieceId = imageInfo.bottomPieceId;
                    ImageInfo bottomImageInfo = imageInfoArray[bottomConnectingPieceId-1];
                    topConnectingX = bottomImageInfo.calculateTopX(bottomImageInfo.imageView.getLeft(),bottomConnectingPieceId);
                    topConnectingY = bottomImageInfo.calculateTopY(bottomImageInfo.imageView.getTop(), bottomConnectingPieceId);
                    diffX = (topConnectingX-bottomConnectingX);
                    diffY = (topConnectingY-bottomConnectingY);
                    if(Math.abs(diffX)<=20 && Math.abs(diffY)<=20)
                    {
                        for(int i=0;i<7;i++)
                            flag[i]=false;
                        updatePosition(imageInfo.id);
                        imageInfo.setIsBottomConnected(true);
                        bottomImageInfo.setIsTopConnected(true);
                        attachedPieces++;
                        if(attachedPieces==5)
                        {
                            setupFinishDialogue();
                            playSound(gameFinishSoundId);
                        }
                        else
                            playSound(correctPieceAttachSoundId);
                    }
                }

                break;

            case MotionEvent.ACTION_MOVE:

                diffX = (int) (event.getRawX() - touchStartX);
                diffY = (int) (event.getRawY() - touchStartY);
                touchStartX = (int)event.getRawX();
                touchStartY = (int)event.getRawY();

                for(int i=0;i<7;i++)
                    flag[i]=false;                  
                updatePosition(imageInfo.id);       
                break;

            default:
                break;
        }

    }

    return true;
}

void lockOrientation()
{
    switch (getResources().getConfiguration().orientation)
    {
        case Configuration.ORIENTATION_PORTRAIT:
            if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.FROYO)
            {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            else 
            {
                int rotation = getWindowManager().getDefaultDisplay().getRotation();
                if(rotation == android.view.Surface.ROTATION_90|| rotation == android.view.Surface.ROTATION_180)
                {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
                }
                else 
                {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            }   
            break;

        case Configuration.ORIENTATION_LANDSCAPE:
            if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.FROYO)
            {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
            else 
            {
                int rotation = getWindowManager().getDefaultDisplay().getRotation();
                if(rotation == android.view.Surface.ROTATION_0 || rotation == android.view.Surface.ROTATION_90){
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                } 
                else 
                {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
                }
            }
            break;
    }
}

void setupFinishDialogue()
{
    /*if(getWindowManager().getDefaultDisplay().getRotation()==3)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    else if(getWindowManager().getDefaultDisplay().getRotation()==1)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
    else if(getWindowManager().getDefaultDisplay().getRotation()==2)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
    else setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);*/


    lockOrientation();

    AlertDialog.Builder builderForAlertBox = new AlertDialog.Builder(this);
    builderForAlertBox.setCancelable(false).setMessage("Good Job!").setPositiveButton("Restart", dialogClickListner).setNegativeButton("Quit", dialogClickListner).
    setCancelable(true).show(); 
}
DialogInterface.OnClickListener dialogClickListner = new DialogInterface.OnClickListener() 
{       
    public void onClick(DialogInterface dialog, int which) 
    {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        switch (which) {
        case DialogInterface.BUTTON_POSITIVE:
            finish();
            Intent intent = new Intent(getApplicationContext(),GameActivity.class);
            startActivity(intent);
            break;

        case DialogInterface.BUTTON_NEGATIVE:
            finish();
        default:
            break;
        }

    }
};

}

ImageInfo Class

package com.example.JigSawPuzzle;

import android.widget.ImageView;
import android.widget.Toast;

public class ImageInfo 
{
ImageView imageView;
int imageATopLeftDifferenceX = -1;
int imageATopLeftDifferenceY = -1;
int imageABottomRightDifferenceX = 113;
int imageABottomRightDifferenceY = 140;

int imageBTopLeftDifferenceX = 0;
int imageBTopLeftDifferenceY = 0;
int imageBBottomRightDifferenceX = 0;
int imageBBottomRightDifferenceY = 111;

int imageCTopLeftDifferenceX = 14;
int imageCTopLeftDifferenceY = 0;
int imageCBottomRightDifferenceX = 0;
int imageCBottomRightDifferenceY = 88;

int imageDTopLeftDifferenceX = 92;
int imageDTopLeftDifferenceY = 2;
int imageDBottomRightDifferenceX = 0;
int imageDBottomRightDifferenceY = 70;

/*int imageETopLeftDifferenceX = 0;
int imageETopLeftDifferenceY = 0;
int imageEBottomRightDifferenceX = 55;
int imageEBottomRightDifferenceY = 112;*/
int imageETopLeftDifferenceX = 55;
int imageETopLeftDifferenceY = 112;
int imageEBottomRightDifferenceX = 0;
int imageEBottomRightDifferenceY = 0;

/*int imageFTopLeftDifferenceX = 0;
int imageFTopLeftDifferenceY = 26;
int imageFBottomRightDifferenceX = 0;
int imageFBottomRightDifferenceY = 109;
int id,topPieceId,bottomPieceId;*/
int imageFTopLeftDifferenceX = 0;
int imageFTopLeftDifferenceY = 109;
int imageFBottomRightDifferenceX = 0;
int imageFBottomRightDifferenceY = 26;
int id,topPieceId,bottomPieceId;

boolean isTopConnected = false;
boolean isBottomConnected = false;
public ImageInfo(int id,ImageView imageView,int topPieceId,int bottomPieceId)
{
    this.topPieceId = topPieceId;
    this.bottomPieceId = bottomPieceId;
    this.imageView = imageView;
    this.id = id;
    if(id==1)
        isTopConnected = true;
    else if(id==6)
        isBottomConnected = true;
    if(GameActivity.screenInches>9.0)
        initializePiecesInfo();
}
private void initializePiecesInfo() 
{

    imageATopLeftDifferenceX = 0;
    imageATopLeftDifferenceY = 0;
    imageABottomRightDifferenceX = 150;
    imageABottomRightDifferenceY = 184;

    imageBTopLeftDifferenceX = 0;
    imageBTopLeftDifferenceY = 0;
    imageBBottomRightDifferenceX = 0;
    imageBBottomRightDifferenceY = 148;

    imageCTopLeftDifferenceX = 23;
    imageCTopLeftDifferenceY = 0;
    imageCBottomRightDifferenceX = 0;
    imageCBottomRightDifferenceY = 115;

    imageDTopLeftDifferenceX = 121;
    imageDTopLeftDifferenceY = 0;
    imageDBottomRightDifferenceX = 0;
    imageDBottomRightDifferenceY = 91;

    /*int imageETopLeftDifferenceX = 0;
    int imageETopLeftDifferenceY = 0;
    int imageEBottomRightDifferenceX = 55;
    int imageEBottomRightDifferenceY = 112;*/
    imageETopLeftDifferenceX = 74;
    imageETopLeftDifferenceY = 147;
    imageEBottomRightDifferenceX = 0;
    imageEBottomRightDifferenceY = 0;

    /*int imageFTopLeftDifferenceX = 0;
    int imageFTopLeftDifferenceY = 26;
    int imageFBottomRightDifferenceX = 0;
    int imageFBottomRightDifferenceY = 109;
    int id,topPieceId,bottomPieceId;*/
    imageFTopLeftDifferenceX = 0;
    imageFTopLeftDifferenceY = 144;
    imageFBottomRightDifferenceX = 0;
    imageFBottomRightDifferenceY = 26;
}

int calculateTopX(int realX,int id)
{
    if(id==2)
        return realX+imageBTopLeftDifferenceX;
    if(id==3)
        return realX+imageCTopLeftDifferenceX;
    if(id==4)
        return realX+imageDTopLeftDifferenceX;
    if(id==5)
        return realX+imageETopLeftDifferenceX;
    if(id==6)
        return realX+imageFTopLeftDifferenceX;
    return realX;

}
int calculateTopY(int realY,int id)
{
    if(id==2)
        return realY+imageBTopLeftDifferenceY;
    if(id==3)
        return realY+imageCTopLeftDifferenceY;
    if(id==4)
        return realY+imageDTopLeftDifferenceY;
    if(id==5)
        return realY+imageETopLeftDifferenceY;
    if(id==6)
        return realY+imageFTopLeftDifferenceY;
    return realY;
}

int calculateBottomX(int realX,int id)
{
    if(id==1)
        return realX+imageABottomRightDifferenceX;
    if(id==2)
        return realX+imageBBottomRightDifferenceX;
    if(id==3)
        return realX+imageCBottomRightDifferenceX;
    if(id==4)
        return realX+imageDBottomRightDifferenceX;
    if(id==5)
        return realX+imageEBottomRightDifferenceX;
    return realX+imageFBottomRightDifferenceX;      
}
int calculateBottomY(int realY,int id)
{
    if(id==1)
        return realY+imageABottomRightDifferenceY;
    if(id==2)
        return realY+imageBBottomRightDifferenceY;
    if(id==3)
        return realY+imageCBottomRightDifferenceY;
    if(id==4)
        return realY+imageDBottomRightDifferenceY;
    if(id==5)
        return realY+imageEBottomRightDifferenceY;
    return realY+imageFBottomRightDifferenceY;
}
void setIsTopConnected(boolean isTopConnected)
{
    this.isTopConnected = isTopConnected;
}
void setIsBottomConnected(boolean isBottomConnected)
{
    this.isBottomConnected = isBottomConnected;
}

}

解决方案

Given the images you provided it is straightforward to connect them in a generic way because the images have the same width and they have transparent background, here is the idea:

1- You need the overlap distance between the two images, which you can calculate from either the bottom or top image

The green line in the bottom picture should be equal to the red line in the top picture

Given that your images have transparent background you can calculate this distance easily, I will use the bottom image here.

The idea is to check every pixel in the last column of the bottom bitmap (i.e. width - 1) and stop once you hit a non-transparent pixel.

 private int getOverlapDistance(Bitmap bottomBitmap) {
    int height = bottomBitmap.getHeight();
    int width = bottomBitmap.getWidth();
    int distance = 0;
    for (int i = 0; i < height; i++) {
        if (Color.alpha(bottomBitmap.getPixel(width - 1, i)) != 0) {
            distance = (i + 1);
            break;
        }
    }
    return distance;
}

To connect them you can do something like (assuming you have separate ImageView for the top and bottom image):

bitmap = ((BitmapDrawable) bottomImage.getDrawable()).getBitmap();
int overlapDistance = getOverlapDistance(bitmap);
bottomImage.setTop(topImage.getBottom() - overlapDistance);

Actually I tried this with a simple activity and it is working, here is how it look like before and after connecting the two images:

I just execute the above code when the button connect is clicked

这篇关于连接在机器人2图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆