2013-09-04 2 views
0

회전, 크기 조절 및 변형을 적용한 후에 캔바스와 일치하도록 내 뷰의 경계를 업데이트하는 방법을 파악하려고합니다.캔버스 변환 후 뷰 경계 업데이트 (회전, 크기 조절, 변형)

이것은 맞춤 텍스트 뷰용 클래스입니다. 내가 원하는대로 회전하지만 뷰가 내 캔버스 주위를 감싸고 있지 않습니다.

public class RDTextView extends TextView { 

public int angle = 0; 

public RDTextView(Context context) { 
    super(context); 
} 

@Override 
protected void onDraw(Canvas canvas) 
{ // Save the current matrix 
    canvas.save(); 
    // Rotate this View at its center 
    canvas.rotate(angle,this.getWidth()/2, this.getHeight()/2); 
    // Draw it --- will add scale 
    super.onDraw(canvas); 
    // Restore to the previous matrix 
    canvas.restore(); 
} 

제 관심사는보기 주위에 테두리가 있지만 각도를 변경하면 캔버스 모양을 따르지 않습니다.

Before rotation After rotation

경계는 회전 후 변경되지 않습니다하지만 난 내용을 일치하도록 업데이트하고 싶습니다.

답변

0

나는 내 요구에 맞게 다음 코드를 만들었습니다.

import java.awt.Graphics; 
    import java.awt.Graphics2D; 

    import javax.swing.JLabel; 


    public class RotatedLabel extends JLabel { 

     //we need to remember original size 
     private int originalWidth = 0; 
     private int originalHeight = 0; 

     //I do rotation around the center of label, so save it too 
     private int originX = 0; 
     private int originY = 0; 

     public RotatedLabel(String text, int horizotalAlignment) { 
      super(text, horizotalAlignment); 
     } 

     @Override 
     public void setBounds(int x, int y, int width, int height) { 
      //save new data 
      originX = x + width/2; 
      originY = y + height/2; 
      originalWidth = width; 
      originalHeight = height; 
      super.setBounds(x, y, width, height); 
     }; 

     @Override 
     public void paint(Graphics g) { 
      Graphics2D g2d = (Graphics2D) g; 

      int w2 = getWidth()/2; 
      int h2 = getHeight()/2; 

      double angle = -Math.PI/2;//it's our angle 

      //now we need to recalculate bounds 
      int newWidth = (int)Math.abs(originalWidth * Math.cos(angle) + originalHeight * Math.sin(angle)); 
      int newHeight = (int)Math.abs(originalWidth * Math.sin(angle) + originalHeight * Math.cos(angle)); 

      g2d.rotate(angle, w2, h2); 
      super.paint(g); 

      //set new bounds 
      super.setBounds(originX - newWidth/2, originY - newHeight/2, newWidth, newHeight); 
     } 
    } 
관련 문제