2013-12-09 47 views
0

我正在將自定義視圖加載到線性佈局中。自定義視圖包含可以放置在線性佈局中的圖像。如何確定圖像定位後哪些像素可見?在自定義視圖中查找圖像位置

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/mainView" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context=".MainActivity" > 


<LinearLayout 
    android:id="@+id/viewPort" 
    android:orientation="horizontal" 
    android:layout_width="700dp" 
    android:layout_height="200dp"> 
</LinearLayout> 

</RelativeLayout> 

而且我的代碼加載圖像:加載視圖

   View touchView = new TouchViewClass(this,mPicturePath); 
      LinearLayout rl = (LinearLayout)this.findViewById(R.id.viewPort); 
      rl.addView(touchView); 
+0

你想要視圖的x和y座標? – Naddy

+0

我需要視圖內圖像的x和y座標。一旦位圖被繪製到畫布上,它可以在佈局中移動。我需要找到相對於佈局的x和y,以便我可以確定哪些部分正在查看。 – TheGeekNess

回答

0

好想通了

public TouchViewClass(Context context, AttributeSet attrs, int defStyle, String picPath) { 
    super(context, attrs, defStyle); 
    this.picPath = picPath; 

    //decode and size the image. 
    mSourceImage = prepareImage(); 
} 
private Bitmap prepareImage(){ 
    //Create bitmap options 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 


    //Create final bitmap with options specifying the new size 
    Bitmap readyImg = BitmapFactory.decodeFile(picPath, options); 

    return readyImg; 
} 
@Override 
public void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 

    canvas.save(); 
    canvas.drawBitmap(mSourceImage, mPosX, mPosY, null); 
    canvas.restore(); 
} 

和我的活動。如果其他人試圖找到一個繪製的圖像後,其被移動繼承人如何我做到了

@Override 
public boolean onTouchEvent(MotionEvent ev) { 
    final int action = ev.getAction(); 
    switch (action & MotionEvent.ACTION_MASK) { 
    case MotionEvent.ACTION_DOWN: { 
     final float x = ev.getX(); 
     final float y = ev.getY(); 

     mLastTouchX = x; 
     mLastTouchY = y; 


     // Save the ID of this pointer 
     mActivePointerId = ev.getPointerId(0); 
     break; 
    } 

    case MotionEvent.ACTION_MOVE: { 
     // Find the index of the active pointer and fetch its position 
     final int pointerIndex = ev.findPointerIndex(mActivePointerId); 
     //Get new location 
     final float x = ev.getX(pointerIndex); 
     final float y = ev.getY(pointerIndex); 

     //Compare to old location 
     final float dx = x - mLastTouchX; 
     final float dy = y - mLastTouchY; 

     //set new resting location 
     mPosX += dx; 
     mPosY += dy; 

     mLastTouchX = x; 
     mLastTouchY = y; 


     invalidate(); 
     break; 
    } 
+0

mPosX和mPosY爲您提供最終位置 – TheGeekNess

相關問題