Поворот изображения на холсте в Android - PullRequest
25 голосов
/ 03 января 2012

Я хочу повернуть изображение в соответствии с определенным углом в Android, что-то вроде компаса ...

У меня есть этот код ... он работает на drawPath () но я хочу заменить путь и рисунок с изображением .. Я пытался создать растровое изображение DrawBitmapImage, но изображение не вращается, как путь .. Любая справка PLease?

public void draw(Canvas canvas) {
    double angle = calculateAngle(currentLongitude, currentLatitude, targetLongitude, targetLatitude);

    //Correction;
    angle-=90;

    //Correction for azimuth
    angle-=azimuth;

    if((getContext() instanceof Activity) && ((Activity)getContext()).getWindowManager().getDefaultDisplay().getOrientation()==Configuration.ORIENTATION_PORTRAIT)angle-=90;

    while(angle<0)angle=angle+360;

    Rect rect = canvas.getClipBounds();

    int height = rect.bottom-rect.top;
    int width = rect.right-rect.left;
    int left = rect.left;
    int top = rect.top;

    if(height>width){
        top+=(height-width)/2;
        height=width;
    }
    if(width>height){
        left+=(width-height)/2;
        width=height;
    }

    float centerwidth = width/2f;
    float centerheight = height/2f;

    Paint p = new Paint();
    p.setColor(color);
    p.setStyle(Paint.Style.FILL);
    p.setAntiAlias(true);

    float startX = left+(float)(centerwidth+Math.cos(deg2rad(angle))*width/3.0);
    float startY = top+(float)(centerheight+Math.sin(deg2rad(angle))*height/3.0);

    Path path = new Path();
    path.moveTo(
            startX,
            startY);
    path.lineTo(
            left+(float)(centerwidth+Math.cos(deg2rad(angle+140))*width/4.0),
            top+(float)(centerheight+Math.sin(deg2rad(angle+140))*height/4.0));
    path.lineTo(
            left+(float)centerwidth,
            top+(float)centerheight
            );
    path.lineTo(
            left+(float)(centerwidth+Math.cos(deg2rad(angle+220))*width/4.0), 
            top+(float)(centerheight+Math.sin(deg2rad(angle+220))*height/4.0)
            );

    path.lineTo(
            startX,
            startY
            );




    canvas.drawPath(path, p);
}

Ответы [ 6 ]

53 голосов
/ 03 января 2012

Вы можете вращать свое растровое изображение при рисовании с использованием матрицы:

Matrix matrix = new Matrix();
matrix.setRotate(angle, imageCenterX, imageCenterY);
yourCanvas.drawBitmap(yourBitmap, matrix, null);

Вы также можете сделать это, повернув холст перед рисованием:

yourCanvas.save(Canvas.MATRIX_SAVE_FLAG); //Saving the canvas and later restoring it so only this image will be rotated.
yourCanvas.rotate(-angle);
yourCanvas.drawBitmap(yourBitmap, left, top, null);
yourCanvas.restore();

Выберите тот, который подходит вам лучше всего.

3 голосов
/ 03 января 2012

Вы должны сначала повернуть холст, а затем нарисовать все, что вы хотите. Тогда нарисованный объект будет отображаться как повернутый на экране.

canvas.rotate(45); // degrees to rotate

попробуй это хорошо.

В этом уроке вы узнаете, как рисовать растровое изображение и как вращать холст

Проверить полное руководство

1 голос
/ 03 февраля 2015

Это единственный, который работал для меня без проблем.

    private Bitmap rotateBitmap(Bitmap bitmap, int rotationAngleDegree){

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int

 newW=w, newH=h;
    if (rotationAngleDegree==90 || rotationAngleDegree==270){
        newW = h;
        newH = w;
    }
    Bitmap rotatedBitmap = Bitmap.createBitmap(newW,newH, bitmap.getConfig());
    Canvas canvas = new Canvas(rotatedBitmap);

    Rect rect = new Rect(0,0,newW, newH);
    Matrix matrix = new Matrix();
    float px = rect.exactCenterX();
    float py = rect.exactCenterY();
    matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
    matrix.postRotate(rotationAngleDegree);
    matrix.postTranslate(px, py);
    canvas.drawBitmap(bitmap, matrix, new Paint( Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG ));
    matrix.reset();

    return rotatedBitmap;
}
1 голос
/ 08 октября 2013

Используйте следующий код. у меня это сработало

Вращение поплавка = 30.0f;

     Bitmap bitmap = your bitmap
     Rect rect = new Rect(100,100,bitmap.width, bitmap.height);
     Matrix matrix = new Matrix();
     float px = rect.exactCenterX();
     float py = rect.exactCenterY();
     matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
     matrix.postRotate(rotation);
     matrix.postTranslate(px, py);
     canvas.drawBitmap(bitmap, matrix, null);
     matrix.reset();
     invalidate();
1 голос
/ 03 января 2012

@ Рехам: посмотрите на этот пример кода ниже,

public class bitmaptest extends Activity {
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    LinearLayout linLayout = new LinearLayout(this);

    // load the origial BitMap (500 x 500 px)
    Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
           R.drawable.android);

    int width = bitmapOrg.width();
    int height = bitmapOrg.height();
    int newWidth = 200;
    int newHeight = 200;

    // calculate the scale - in this case = 0.4f
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;

    // createa matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);
    // rotate the Bitmap
    matrix.postRotate(45);

    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
                      width, height, matrix, true);

    // make a Drawable from Bitmap to allow to set the BitMap
    // to the ImageView, ImageButton or what ever
    BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);

    ImageView imageView = new ImageView(this);

    // set the Drawable on the ImageView
    imageView.setImageDrawable(bmd);

    // center the Image
    imageView.setScaleType(ScaleType.CENTER);

    // add ImageView to the Layout
    linLayout.addView(imageView,
            new LinearLayout.LayoutParams(
                  LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT
            )
    );

    // set LinearLayout as ContentView
    setContentView(linLayout);
}
}

Вы должны использовать матрицу для поворота изображения, смотреть линии

matrix.postRotate(45); -

это повернет изображение на 45 градусов

Надеюсь, это поможет вам ... THX

0 голосов
/ 31 марта 2019

На основе кода @Sakthi, но добавьте scaling :)

        Rect rect = new Rect(0,0,canvas.getWidth(), canvas.getHeight());
        Matrix matrix = new Matrix();
        matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
        matrix.postScale(
                ((float)rect.width()) / bitmap.getWidth(),
                ((float)rect.height()) / bitmap.getHeight());
        matrix.postRotate(180);
        matrix.postTranslate(rect.exactCenterX(), rect.exactCenterY());
        canvas.drawBitmap(bitmap, matrix, null);
...