使用AffineTransform旋转图像

我上课了Airplane。在这个类中,我有img一个BufferedImage类型的变量。更重要的是,我有WorldMap重写功能的类paintComponent(Graphics g):


@Override

public void paintComponent(Graphics g) {

    Graphics2D g2d = (Graphics2D) g;

    g2d.drawImage(mapa, 0, 0, getWidth(), getHeight(), null); 

    drawAirplanes(g2d);

}

函数drawAirplanes()看起来像这样:


private void drawAirplane(Graphics2D g){

    for(Samolot i: s){

        i.rotateAirplane();

        g.drawImage(i.getImg(),i.getX(),i.getY(),(int)i.getDim().getWidth(),(int)i.getDim().getHeight(),  null);

    }

}

它只需要1)旋转飞机(飞机对象内部的BufferedImage)2)画他。


我的Airplane.rotateAirplane()函数如下所示:


 public void rotateSamolot() {

   AffineTransform tx = new AffineTransform();


   tx.translate(10,10); //10, 10 is height and width of img divide by 2

   tx.rotate(Math.PI / 2);

   tx.translate(-10,-10); 


   AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);


   BufferedImage newImage =new BufferedImage(20, 20, img.getType()); //20, 20 is a height and width of img ofc

   op.filter(img, newImage);


       this.img = newImage;

 }

我运行我的程序时,只有ofc mapa对象被绘制。当我删除此车道时


this.img = newImage;


我也有我的飞机,但是没有旋转。


智慧大石
浏览 1153回答 2
2回答

阿晨1998

这是对我有用的(从这里到那里复制副本):public BufferedImage rotateImag (BufferedImage imag, int n) { //n rotation in gradians        double rotationRequired = Math.toRadians (n);        double locationX = imag.getWidth() / 2;        double locationY = imag.getHeight() / 2;        AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);                BufferedImage newImage =new BufferedImage(imag.getWidth(), imag.getHeight(), imag.getType()); //20, 20 is a height and width of imag ofc       op.filter(imag, newImage);           //this.img = newImage;       return(newImage);     }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java