在android中的画布上旋转图像

Reh*_*ham 27 android angle rotation android-canvas

我想根据android中的特定角度旋转图像,有些像指南针...

我有这个代码...它适用于drawPath(),但我想用图像替换路径和绘图的东西..我试图创建一个位图图像,DrawBitmapImage,但图像不像路径一样旋转..任何请帮忙?

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);
}
Run Code Online (Sandbox Code Playgroud)

Jav*_*ave 55

您可以使用矩阵绘制位图时旋转位图:

Matrix matrix = new Matrix();
matrix.setRotate(angle, imageCenterX, imageCenterY);
yourCanvas.drawBitmap(yourBitmap, matrix, null);
Run Code Online (Sandbox Code Playgroud)

您也可以在绘制之前旋转画布来执行此操作:

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();
Run Code Online (Sandbox Code Playgroud)

选择最适合你的.


Yug*_*abu 5

你必须先旋转画布,然后画出你想要的任何东西。然后绘制的对象将在屏幕上旋转显示。

canvas.rotate(45); // degrees to rotate
Run Code Online (Sandbox Code Playgroud)

试试这个好方法。

查看本教程,您将获得有关如何绘制位图以及如何旋转画布的信息

检查完整教程