簡體   English   中英

Android旋轉位圖並繪制畫布

[英]Android rotate Bitmap and draw Canvas

我正在嘗試使用matrix旋轉位圖。 然后我試圖在畫布上繪制它。 但這只是消失了!

這是我的代碼如下:

    public class MultitouchView extends View {

private static final int INVALID_POINTER_ID = -1;
private static final String TAG = "MultitouchView";
private Drawable image;
private Drawable userImage;

Bitmap userOriginal;
Bitmap userResult;

private float scaleFactor = 1.0f;
private ScaleGestureDetector scaleGestureDetector;

private float mPosX;
private float mPosY;

private float mLastTouchX;
private float mLastTouchY;
private int mActivePointerId = INVALID_POINTER_ID;

private int direction = 0;

Context context;

public MultitouchView(Context context) {
    super(context);
    image = context.getResources().getDrawable(
            R.drawable.plain_black_wallpaper);
    image.setBounds(0, 0, image.getIntrinsicWidth(),
            image.getIntrinsicHeight());

    userOriginal = BitmapFactory.decodeResource(this.getResources(), R.drawable.navigation);

    userImage = context.getResources().getDrawable(R.drawable.navigation);
    userImage.setBounds(500, 500, 550, 550);

    setFocusable(true);

    scaleGestureDetector = new ScaleGestureDetector(context,
            new ScaleListener());
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // Set the image bounderies
    canvas.save();
    //scale canvas
    canvas.scale(scaleFactor, scaleFactor);
    image.draw(canvas);
    canvas.translate(mPosX, mPosY);

    //rotate user drawable

    userImage.draw(canvas);

    canvas.restore();
}

 public void setDirection(int direction) {
        this.direction = direction;
        rotateBitmap();
        invalidate();
      }

private void rotateBitmap() {
    Matrix matrix = new Matrix();
    matrix.postRotate(this.direction);
    userResult = Bitmap.createBitmap(userOriginal,0,0, userOriginal.getWidth(), userOriginal.getHeight(), matrix,true);
    userImage=new BitmapDrawable(this.getResources(),userResult);

}

}

我已經刪除了比例畫布和事件監聽器等功能。 使代碼小巧易讀。

我會定期調用setDirection方法,但是在調用該方法之后,可繪制對象“ userImage”就消失了。 任何人都可以請教一下這里出了什么問題..

謝謝

因此,我發現了問題所在。.旋轉位圖工作正常,但是由於我未在drawable上設置邊界,因此“ userImage” drawable在位置0,0處繪制,高度和寬度為0,0,因此消失。 我通過更改hte旋轉位圖函數進行了修復,如下所示:

private void rotateBitmap() {
    Matrix matrix = new Matrix();
    matrix.postRotate(this.direction);
    userResult = Bitmap.createBitmap(userOriginal,0,0, userOriginal.getWidth(), userOriginal.getHeight(), matrix,true);
    userImage=new BitmapDrawable(this.getResources(),userResult);
    userImage.setBounds(500, 500, 550, 550);

}

需要實現userImage.Setbounds ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM