2017-06-29 100 views
0

我想繪製ImageView(就像一個簡單的繪畫,但只是在圖像上)。我創建了一個自定義的MyImageView類,它擴展了ImageView,我重寫了onDraw。我希望ImageView位於屏幕的中心。在ImageView上繪圖

當我使用一種佈局時,圖像出現在左上角,我可以在上面畫出沒有問題的圖像。

enter image description here

當我使用不同的佈局,圖像出現在屏幕中央畫布仍然停留在左上角這個小的小矩形。因此,當我嘗試繪製圖像時,我只能在左上角進行繪製,並在中間的圖像上顯示變化。

enter image description here

在我的MainActivity我設置:

myImageView = (MyImageView) findViewById(R.id.pdfView); 

// I also extract the bitmap myBitmap from the pdf ... 
// and pass it to the ImageView 
myImageView.setImageBitmap(myBitmap); 

// and I set the Canvas too: 
Canvas myCanvas = new Canvas(myBitmap); 
myImageView.setMyCanvas(myCanvas); 

然後這裏是MyImageView的關鍵部分:

public class MyImageView extends 
    android.support.v7.widget.AppCompatImageView { 

    // variables... 

    public MyImageView(Context context, @Nullable AttributeSet attrs) { 
     super(context, attrs); 
     setupDrawing(); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 
     canvas.drawPath(drawPath, drawPaint); 
    } 

    private void setupDrawing() { //...usual stuff here } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { //...usual stuff here } 

    public void setMyCanvas(Canvas canvas) { this.myCanvas = canvas; } 

我一定要在MyImageView或添加/更改某事MainActivity,以便畫布僅位於ImageView的頂部或至少在整個屏幕上延伸?

+0

你可以在這裏添加你的onDraw()方法的代碼。你有硬編碼的價值嗎?另外,第二種情況看起來像是將寬度和高度設置爲匹配圖像視圖的match_parent,這就是爲什麼您將整個區域作爲畫布。 – user2520215

+0

我想加入 android:gravity =「center」 到你的線性佈局應該使它按照需要工作。 – user2520215

回答

0

for,ImageView將在屏幕中心。修改您的佈局如下

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical" 
     android:gravity="center" 
     android:background="#EEEEEE"> 

     <com.example.android.samplepaint.MyImageView 
      android:id="@+id/pdfView" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:scaleType="fitXY" 
      android:layout_gravity="center_horizontal" 
      android:background="@android:color/white" /> 
</LinearLayout> 
1

畫布原點和ImageView scaleType或重力之間沒有關係。

畫布的X,Y原點始終是視圖的左上角,如果您想在視圖的其他部分進行繪製,則需要自行翻譯座標。

ADDED 首先要理解的是,畫布不僅用於繪製所有視圖,而且還用於繪製您選擇的圖像。

居中路徑繪製,那麼你需要做這樣的事情在你的onDraw不是一個規劃問題

canvas.save(); 
canvas.translate((getWidth() - pathWidth)/2, (getHeight() - pathHeight)/2); 
canvas.drawPath(drawPath, drawPaint); 
canvas.restore(); 

更多的是算術之一。

+0

我更新了我的問題,請您詳細說明您的答案。 – Camille

+0

我編輯了我的答案。 –

+0

謝謝。在這種情況下,pathWidth和pathHeight是什麼? – Camille

0

我認爲原因在於您的佈局選擇。由於屏幕適應的問題,每個佈局需要綁定到元素,而某些佈局默認爲左上角。