AffineTransform rotate+resize+center
I have an image in landscape format. This image should be rotated 90 degrees (into portrait format) then resized to fit screen (by height) and finally centered on the screen. I'll like to use AffineTransform to do this task, but I cannot figure out have to make the translation so the picture is centered on the screen.
What is needed to make the following code work?
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.geom.*;
public class RotateAndResize extends JFrame
public static Image image;
public static void main(String[] args) throws Exception
//A photo (in landscape format) which need to be rotated 90 degress (to portrait format)
File thumbFile = new File("C:\\...\\P1080309.jpg");
image = javax.imageio.ImageIO.read(thumbFile);
RotateAndResize frame = new RotateAndResize();
frame.setSize(800,600);
frame.setVisible(true);
public void update ( Graphics g )
paint(g);
public void paint(Graphics in)
Graphics2D g = (Graphics2D) in;
int w = getWidth();
int h = getHeight();
int imgWidth = image.getWidth(null);
int imgHeight = image.getHeight(null);
g.setColor (new Color(0,0,0));
g.fillRect (0,0,w,h);
//switch due to rotation
int tmp = imgHeight;
imgHeight = imgWidth;
imgWidth = tmp;
double scale = Math.min((double)w/imgWidth, (double)h/imgHeight);
AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
at.quadrantRotate(1); //90
g.setTransform ( at );
g.drawImage(image
,w/2 - imgWidth / 2 //center
,h/2 - imgHeight / 2 //center
,imgWidth
,imgHeight
,null);
}
First and foremost:
1. Always create and show Swing components on the EDT using SwingUtilities (or EventQueue) #invokeLater.
2. Never draw to a JFrame, it's a top level container and is meant to hold other components. Do custom painting in a JCompoent or JPanel subclass. See [the Tutorial|http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html].
3. Your GUI is not a special type of JFrame and should not subclass JFrame. Always prefer composition over inheritance.
Is this an exercise to use AffineTransform? I usually find it easier to work with the Graphics2D API.import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class LandscapeToPortrait {
Image image;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new LandscapeToPortrait().makeUI();
public void makeUI() {
try {
// change the filename to your image file
image = ImageIO.read(new File(
"E:/TestImage.jpg"));
// scale to screen size, landscape mode
image = image.getScaledInstance(800, 600, Image.SCALE_SMOOTH);
} catch (IOException ex) {
ex.printStackTrace();
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
int panelWidth = getWidth();
int panelHeight = getHeight();
double scale = (double) panelHeight / imageWidth;
Graphics2D g2 = (Graphics2D) g.create();
// translate to the center of the panel
g2.translate(panelWidth / 2, panelHeight / 2);
// rotate 90°
g2.rotate(Math.PI / 2);
// translate to the point where the top-right of the
// image should paint. Remember that when rotated 90°,
// +x -> +y and +y -> -x
// [0,5] [0,0]
// +----------------+
// | |
// | |
// | |
// | |
// | |
// | |
// | |
// +----------------+
// [5,5] [5,0]
// Also remember that the image will be scaled when painted
g2.translate(-panelHeight / 2, -imageHeight * scale / 2);
// apply the scale
g2.scale(scale, scale);
g2.drawImage(image, 0, 0, this);
g2.dispose();
panel.setPreferredSize(new Dimension(400, 400));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}db
Similar Messages
-
Open Tiff, rotate, resize and save as JPEG (using JAI)
I 'm having a hard time getting my arms around the JAI classes to perform
this transform. I've looked at the tutorial and api, etc and did not get
very far.
I have the code to open the TIFF, and save as a JPEG. My question is how to
go from there to do the manipulations (rotate, resize)?
If anyone knows how to do this with JAI classes, please let me know.
Thanks,
Bill Pfeiffer
My code:
try
SeekableStream input = new FileSeekableStream("C:\\S1000000.TIF");
FileOutputStream output = new FileOutputStream
("C:\\S1000000.jpg");
TIFFDecodeParam TIFFparam = new TIFFDecodeParam();
ImageDecoder decoder = ImageCodec.createImageDecoder("tiff",
input ,TIFFparam);
JPEGEncodeParam JPEGparam = new
JPEGEncodeParam();
ImageEncoder encoder = ImageCodec.createImageEncoder
("jpeg",output,JPEGparam);
RenderedImage ri = decoder.decodeAsRenderedImage();
encoder.encode(ri);
input.close();
output.close();
catch (IOException e)
e.printStackTrace();For Rotation....
1) add the following function to your code.
private RenderedImage rotate(int degrees, RenderedImage src, Interpolation interpRotate) {
try {
float radians = (float)(degrees * (Math.PI/180.0F));
ParameterBlock pb = new ParameterBlock();
pb.addSource(src);
pb.add(0.0F);
pb.add(0.0F);
pb.add(radians);
pb.add(interpRotate);
src = (RenderedImage)JAI.create("rotate", pb, null);
pb = new ParameterBlock();
pb.addSource(src);
pb.add((float)-(src.getMinX()));
pb.add((float)-(src.getMinY()));
pb.add(interpRotate);
return (RenderedImage)JAI.create("translate", pb, null);
}catch (Exception e) {
return src;
2. call this function before the "encoder.encode(ri);" line in your code. I pass "new InterpolationBilinear()" for the interpolation parameter of the function.
For scaling...
1) add the following lines to your code after or before you rotate the image.
ParameterBlock pb = new ParameterBlock();
pb.addSource(ri);
pb.add(1.1F); //play with these 4 lines to make the image bigger or smaller (1.0F is actual size)
pb.add(1.1F);
pb.add(0.0F);
pb.add(0.0F);
pb.add(new InterpolationNearest() );
t = (RenderedImage) JAI.create("scale",pb,null);
hope this helps. Just play with it a bit. You'll get it. -
IPad 1 has a rotating icon center of screen, iPad 1 has a rotating icon center of screen
iPad 1 has a rotating circle in the center of the screen won't turn off
Try a reset:
Hold the Sleep and Home button down for about 10 second until you see the Apple logo. -
Hi,
I found an interesting tutorial (link) and created a working model, adapting it as needed.
So far, when I center the container sprite and rotate it, it appears to first rotate from a 0,0 registration point, instead of from its center. I've tried to changet he sprite's registration point, but so far this hasn't worked/helped. Nothing else has worked to fix this rotation problem.
I must be doing something wrong.
Here's the AS3 (to view, add to first frame of new FLA, 1024X768 stage, color black). Rotation segments below are commented as //ROTATION.:
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.text.TextField;
//import flash.geom.ColorTransform;
stop();
//public class bejewelled extends Sprite {
var gems_array:Array=new Array();
var aGem:Sprite;
var selectorBox:Sprite=new Sprite();
var selectorRow:int=-10;
var selectorColumn:int=-10;
var red:uint = 0xFF0000;
var green:uint = 0xFF00;
var blue:uint = 0xFF;
var yellow:uint = 0xFFFF00;
var cyan:uint = 0xFFFF;
var magenta:uint = 0xFF00FF;
var white:uint = 0xFFFFFF;
var colours_array:Array=new Array(red,green,blue,yellow,cyan,magenta,white);
var clickPossible:Boolean=false;
var score_txt:TextField=new TextField();
var hint_txt:TextField=new TextField();
var score:uint=0;
var inaRow:uint=0;
var match:Boolean = true;
var gemSize:uint = 96;
var format:TextFormat = new TextFormat();
var rotate:Boolean=false;
var container:Sprite = new Sprite(); // Create the container sprite
//var newColorTransform:ColorTransform = exitBtn.transform.colorTransform;
//newColorTransform.color = 0xff0000;
//exitBtn.transform.colorTransform = newColorTransform;
function bejewelled() {
// Game initiation
format.size = 40;
format.font = 'Arial';
// Create and style score text
addChild(score_txt);
score_txt.textColor=0xFFFFFF;
score_txt.x=gemSize*9.6;
score_txt.autoSize = TextFieldAutoSize.LEFT;
score_txt.defaultTextFormat = format;
// Create and style hint text
addChild(hint_txt);
hint_txt.textColor=0xFFFFFF;
hint_txt.x=gemSize*9.6;
hint_txt.y=gemSize;
hint_txt.autoSize = TextFieldAutoSize.LEFT;
hint_txt.defaultTextFormat = format;
// Create Gems in rows and columns
addChild(container); // Add the container to the display list (stage)
for (var i:uint=0; i<8; i++) {
gems_array[i]=new Array();
for (var j:uint=0; j<8; j++) {
do {
gems_array[i][j]=Math.floor(Math.random()*7);
while (rowLineLength(i,j)>2 || columnLineLength(i,j)>2);
aGem=new Sprite();
aGem.graphics.beginFill(colours_array[gems_array[i][j]]);
aGem.graphics.drawCircle(gemSize/2,gemSize/2,gemSize/2.07);
aGem.graphics.endFill();
aGem.name=i+"_"+j;
aGem.x=j*gemSize;
aGem.y=i*gemSize;
container.addChild(aGem);
//Center the container sprite
container.width = container.width - 10;
container.height = container.height - 10;
container.x = (stage.stageWidth-container.width)/2;
container.y = (stage.stageHeight-container.height)/2;
// Create and style selector box
container.addChild(selectorBox);
selectorBox.graphics.lineStyle(2,red,1);
selectorBox.graphics.drawRect(0,0,gemSize,gemSize);
selectorBox.visible=false;
// Listen for user input
container.addEventListener(MouseEvent.CLICK,onClick);
addEventListener(Event.ENTER_FRAME,everyFrame);
// Every frame...
function everyFrame(e:Event):void {
//Assume that gems are not falling
var gemsAreFalling:Boolean=false;
// Check each gem for space below it
for (var i:int=6; i>=0; i--) {
for (var j:uint=0; j<8; j++) {
// If a spot contains a gem, and has an empty space below...
if (gems_array[i][j] != -1 && gems_array[i+1][j]==-1) {
// Set gems falling
gemsAreFalling=true;
gems_array[i+1][j]=gems_array[i][j];
gems_array[i][j]=-1;
trace("#");
trace(i+"_"+j);
container.getChildByName(i+"_"+j).y+=gemSize;
container.getChildByName(i+"_"+j).name=(i+1)+"_"+j;
break;
// If a gem is falling
if (gemsAreFalling) {
// don't allow any more to start falling
break;
// If no gems are falling
if (! gemsAreFalling) {
// Assume no new gems are needed
var needNewGem:Boolean=false;
// but check all spaces...
for (i=7; i>=0; i--) {
for (j=0; j<8; j++) {
// and if a spot is empty
if (gems_array[i][j]==-1) {
// now we know we need a new gem
needNewGem=true;
// pick a random color for the gem
gems_array[0][j]=Math.floor(Math.random()*7);
// create the gem
aGem=new Sprite();
aGem.graphics.beginFill(colours_array[gems_array[0][j]]);
aGem.graphics.drawCircle(gemSize/2,gemSize/2,gemSize/2.07);
aGem.graphics.endFill();
// ID it
aGem.name="0_"+j;
// position it
aGem.x=j*gemSize;
aGem.y=0;
// show it
container.addChild(aGem);
// stop creating new gems
break;
// if a new gem was created, stop checking
if (needNewGem) {
break;
// If no new gems were needed...
if (! needNewGem) {
// assume no more/new lines are on the board
var moreLinesAvailable:Boolean=false;
// check all gems
for (i=7; i>=0; i--) {
for (j=0; j<8; j++) {
// if a line is found
if (rowLineLength(i,j)>2 || columnLineLength(i,j)>2) {
// then we know more lines are available
moreLinesAvailable=true;
// creat a new array, set the gem type of the line, and where it is
var lineGems:Array=[i+"_"+j];
var gemType:uint=gems_array[i][j];
var linePosition:int;
// check t's a horizontal line...
if (rowLineLength(i,j)>2) {
// if so, find our how long it is and put all the line's gems into the array
linePosition=j;
while (sameGemIsHere(gemType,i,linePosition-1)) {
linePosition--;
lineGems.push(i+"_"+linePosition);
linePosition=j;
while (sameGemIsHere(gemType,i,linePosition+1)) {
linePosition++;
lineGems.push(i+"_"+linePosition);
// check t's a vertical line...
if (columnLineLength(i,j)>2) {
// if so, find our how long it is and put all the line's gems into the array
linePosition=i;
while (sameGemIsHere(gemType,linePosition-1,j)) {
linePosition--;
lineGems.push(linePosition+"_"+j);
linePosition=i;
while (sameGemIsHere(gemType,linePosition+1,j)) {
linePosition++;
lineGems.push(linePosition+"_"+j);
// for all gems in the line...
for (i=0; i<lineGems.length; i++) {
// remove it from the program
container.removeChild(container.getChildByName(lineGems[i]));
// find where it was in the array
var cd:Array=lineGems[i].split("_");
// set it to an empty gem space
gems_array[cd[0]][cd[1]]=-1;
// set the new score
score+=inaRow;
// set the score setter up
inaRow++;
// if a row was made, stop the loop
break;
// if a line was made, stop making more lines
if (moreLinesAvailable) {
break;
// if no more lines were available...
//ROTATION
if (! moreLinesAvailable) {
if(rotate){
container.rotation+=5;
if(container.rotation%90==0){
rotate=false;
container.rotation=0;
rotateClockwise(gems_array);
while(container.numChildren>0){
container.removeChildAt(0);
for (i=0; i<8; i++) {
for (j=0; j<8; j++) {
aGem=new Sprite();
aGem.graphics.beginFill(colours_array[gems_array[i][j]]);
aGem.graphics.drawCircle(gemSize/2,gemSize/2,gemSize/2.07);
aGem.graphics.endFill();
aGem.name=i+"_"+j;
aGem.x=j*gemSize;
aGem.y=i*gemSize;
container.addChild(aGem);
container.addChild(selectorBox);
selectorBox.graphics.lineStyle(2,red,1);
selectorBox.graphics.drawRect(0,0,gemSize,gemSize);
selectorBox.visible=false;
else{
// allow new moves to be made
clickPossible=true;
// remove score multiplier
inaRow=0;
// display new score
score_txt.text=score.toString();
// When the user clicks
function onClick(e:MouseEvent):void {
// If a click is allowed
if (clickPossible) {
// If the click is within the game area...
if (mouseX<container.x+gemSize*8 && mouseX>0 && mouseY<container.y+gemSize*8 && mouseY>0) {
// Find which row and column were clicked
var clickedRow:uint=Math.floor((mouseY-container.y)/gemSize);
//var clickedRow:uint=Math.floor(e.target.y/gemSize);
var clickedColumn:uint=Math.floor((mouseX-container.x)/gemSize);
//var clickedColumn:uint=Math.floor(e.target.x/gemSize);
// Check if the clicked gem is adjacent to the selector
// If not...
if (!(((clickedRow==selectorRow+1 || clickedRow==selectorRow-1)&&clickedColumn==selectorColumn)||((clickedColumn==selectorColumn+1 || clickedColumn==selectorColumn-1) && clickedRow==selectorRow))) {
// Find row and colum the selector should move to
selectorRow=clickedRow;
selectorColumn=clickedColumn;
// Move it to the chosen position
selectorBox.x=gemSize*selectorColumn;
selectorBox.y=gemSize*selectorRow;
// If hidden, show it.
selectorBox.visible=true;
// If it is not next to it...
else {
// Swap the gems;
swapGems(selectorRow,selectorColumn,clickedRow,clickedColumn);
// If they make a line...
if (rowLineLength(selectorRow,selectorColumn)>2 || columnLineLength(selectorRow,selectorColumn)>2||rowLineLength(clickedRow,clickedColumn)>2 || columnLineLength(clickedRow,clickedColumn)>2) {
// remove the hint text
hint_txt.text="";
// dis-allow a new move until cascade has ended (removes glitches)
clickPossible=false;
// move and rename the gems
container.getChildByName(selectorRow+"_"+selectorColumn).x=e.target.x;//clickedColumn*gemSize;
container.getChildByName(selectorRow+"_"+selectorColumn).y=e.target.y;//clickedRow*gemSize;
container.getChildByName(selectorRow+"_"+selectorColumn).name="t";
container.getChildByName(clickedRow+"_"+clickedColumn).x=selectorColumn*gemSize;
container.getChildByName(clickedRow+"_"+clickedColumn).y=selectorRow*gemSize;
container.getChildByName(clickedRow+"_"+clickedColumn).name=selectorRow+"_"+selectorColumn;
container.getChildByName("t").name=clickedRow+"_"+clickedColumn;
match = true;
rotate = true;
// If not...
else {
// Switch them back
swapGems(selectorRow,selectorColumn,clickedRow,clickedColumn);
match = false;
if (match) {
// Move the selector position to default
selectorRow=-10;
selectorColumn=-10;
// and hide it
selectorBox.visible=false;
else {
// Set the selector position
selectorRow=clickedRow;
selectorColumn=clickedColumn;
// Move the box into position
selectorBox.x=gemSize*selectorColumn;
selectorBox.y=gemSize*selectorRow;
match = false;
// If hidden, show it.
selectorBox.visible=true;
// If the click is outside the game area
else {
// For gems in all rows...
for (var i:uint=0; i<8; i++) {
// and columns...
for (var j:uint=0; j<8; j++) {
// if they're not too close to the side...
if (i<7) {
// swap them horizontally
swapGems(i,j,i+1,j);
// check if they form a line
if ((rowLineLength(i,j)>2||columnLineLength(i,j)>2||rowLineLength(i+1,j)>2||columnLineLength(i+1,j)>2)) {
// if so, name the move made
selectorBox.x = j*gemSize;
selectorBox.y = i*gemSize;
selectorBox.visible = true;
hint_txt.text = (i+1).toString()+","+(j+1).toString()+"->"+(i+2).toString()+","+(j+1).toString();
// swap the gems back
swapGems(i,j,i+1,j);
// then if they're not to close to the bottom...
if (j<7) {
// swap it vertically
swapGems(i,j,i,j+1);
// check if it forms a line
if ((rowLineLength(i,j)>2||columnLineLength(i,j)>2||rowLineLength(i,j+1)>2||columnLineLength(i,j+1)>2) ) {
// if so, name it
selectorBox.x = j*gemSize;
selectorBox.y = i*gemSize;
selectorBox.visible = true;
hint_txt.text = (i+1).toString()+","+(j+1).toString()+"->"+(i+1).toString()+","+(j+2).toString();
// swap the gems back
swapGems(i,j,i,j+1);
//Swap given gems
function swapGems(fromRow:uint,fromColumn:uint,toRow:uint,toColumn:uint):void {
//Save the original position
var originalPosition:uint=gems_array[fromRow][fromColumn];
//Move original gem to new position
gems_array[fromRow][fromColumn]=gems_array[toRow][toColumn];
//move second gem to saved, original gem's position
gems_array[toRow][toColumn]=originalPosition;
//Find out if there us a horizontal line
function rowLineLength(row:uint,column:uint):uint {
var gemType:uint=gems_array[row][column];
var lineLength:uint=1;
var checkColumn:int=column;
//check how far left it extends
while (sameGemIsHere(gemType,row,checkColumn-1)) {
checkColumn--;
lineLength++;
checkColumn=column;
//check how far right it extends
while (sameGemIsHere(gemType,row,checkColumn+1)) {
checkColumn++;
lineLength++;
// return total line length
return (lineLength);
//Find out if there us a vertical line
function columnLineLength(row:uint,column:uint):uint {
var gemType:uint=gems_array[row][column];
var lineLength:uint=1;
var checkRow:int=row;
//check how low it extends
while (sameGemIsHere(gemType,checkRow-1,column)) {
checkRow--;
lineLength++;
//check how high it extends
checkRow=row;
while (sameGemIsHere(gemType,checkRow+1,column)) {
checkRow++;
lineLength++;
// return total line length
return (lineLength);
function sameGemIsHere(gemType:uint,row:int,column:int):Boolean {
//Check there are gems in the chosen row
if (gems_array[row]==null) {
return false;
//If there are, check if there is a gem in the chosen slot
if (gems_array[row][column]==null) {
return false;
//If there is, check if it's the same as the chosen gem type
return gemType==gems_array[row][column];
//ROTATION
function rotateClockwise(a:Array):void {
var n:int=a.length;
for (var i:int=0; i<n/2; i++) {
for (var j:int=i; j<n-i-1; j++) {
var tmp:String=a[i][j];
a[i][j]=a[n-j-1][i];
a[n-j-1][i]=a[n-i-1][n-j-1];
a[n-i-1][n-j-1]=a[j][n-i-1];
a[j][n-i-1]=tmp;
bejewelled();
Any help appreciated.OK, way too much code. By default, everything will rotate from top left. If you want to change that you need to change the positions of the content within the container, not the container itself.
For example if you do something like this:
var a:Sprite = new Sprite(); //container
addChild(a);
a.x = 100; a.y = 100;
var b:MovieClip = new car(); //clip from library
a.addChild(b);
addEventListener(Event.ENTER_FRAME, up);
function up(e:Event):void
a.rotation += 1;
The car added to the container will rotate about it's top left point... because that's where the container rotates about. To fix, move the car so the containers top/left is at the car's center like so:
var a:Sprite = new Sprite();
addChild(a);
a.x = 100; a.y = 100;
var b:MovieClip = new car();
a.addChild(b);
b.x -= b.width / 2;
b.y -= b.height / 2;
addEventListener(Event.ENTER_FRAME, up);
function up(e:Event):void
a.rotation += 1;
You'll notice all that changed is moving the car 1/2 it's width and height.
HTH -
HOW TO: Action to resize & center crop images of various sizes
Hello,
I've gotten a lot of help here over the years so I wanted to share an action I created. I needed to resize and automatically center crop images of various sizes for my company's website. For example: All images needed to be 900px x 460px 72dpi - and because input images were from many different sources, the dimensions were different for each image. It seemed straight forward at first (sort of) but I couldn't find a way of doing this without a script or some third party program - so I came up with the following action. Hope someone gets some use out of it.
Note: Change action as needed to suit your needs.
Resize and Center Crop (Auto)
Fit Image
height: 900px
width: 900px
With Don't Enlarge
Canvas Size
height: 460px
vertical: center
extension color: white
Image Size
width: 900px
resolution: 72 per inch
with scale styles
with constrain proportions
Save (optional)
As: JPEG
Quality: 12
Scans: 5 (for web images)
This assumes that the images are at least horizontal, but if you have photoshop CC you can create a conditional action that will work with vertical and horizontal images. If you are square cropping, this action makes it a breeze. I also have an action that uses the same basic logic, but lets me manually move the crop box. The only real issue I have encountered is when the original image ratio is very narrow, which leads to some white space on the top and bottom (I'm working on updating the action to address this). But it has worked on about 95% of my images. Again, you will probably need to adjust all of the variables depending on what you are trying to do, but it should be possible with the same steps. And of course this can also be used to batch process.
Feel free to let me know if anyone comes up with improvements! ThanksHmm thanks Mylenium, I got that response a lot when I was searching before. But if you re-read above, I am explaining a method of doing it without a script. So it wasn't really a question, just a tip in case anyone else wanted to do the same.
-
AffineTransform rotate corrupting images
The picture pretty much shows what is happening.
Im using AffineTransform to rotate the image.
[>>>>PICTURE<<<<|http://img519.imageshack.us/img519/1933/corruptednq1.jpg]
thanks
Edited by: JamesBarnes on Apr 27, 2008 9:02 AM
Edited by: JamesBarnes on Apr 27, 2008 9:05 AMNo need for a new topic, your old one's still alive.
[t-5290271]
db -
Hi,
CS3: I have a 900x800 movie that I'd like to be 900x600. But
when I change the movie size, it crops only from the bottom, I'd
like to center everything. I tried resizing to "content", but that
made it huge...
Does anyone know how to either crop to the middle of the
stage, or move everything? I tried highlighting all the frames in
the movie and moving everything up, but that only did part of the
movie.
Thanks!!!> Does anyone know how to either crop to the middle of the
stage, or move
> everything? I tried highlighting all the frames in the
movie and moving
> everything up, but that only did part of the movie.
You're on the right track with what you've done so far.
Unfortunately,
there isn't a fix-all for this. You'll have to go through and
do it
manually with some items on the stage. It is always a good
practice to make
sure you have the stage the size you want before doing major
design work
that will effect the overall swf.
Dan Smith > adobe community expert
Flash Helps >
http://www.smithmediafusion.com/blog/?cat=11
http://www.dsmith.tv -
Ctrl + t shortcut to enable quick rotations, resizing, etc.
In Photoshop 6.0, if I had the Move tool selected, I was able to make an outline with fouv squares appear around my image by pressing ctrl + t. I was then able to shrink the image, rotate it, etc., by grabbing the four squares that appeared around the image and moving them.
Ctrl + t no longer appears to work in CS6. Is there a new shortcut?You are right. It was not working for me because the layer was locked.
-
Rotate/resize arrows missing
Yes my bounding boxes are on, yes I have deleted preferences.
Running CS6 on a MacBook Pro with OS10.10Resize and rotate magically back again, and I have done nothing. What is different is: my intous is not hooked up (via usb hub) and my macbook is not hooked up to an external monitor. This makes me think it is a compatibility issue with the intous. Will try to hook up intous and monitor separately and see what exactly causes the issue.
-
Resizing a rotated BufferedImage
Hi everybody,
I am currently developing a graphical figure editor. Users can drop several 'objects' on a JPanel.
These objects are represented on screen by BufferedImages. The objects are resizable, rotatable
and movable.
Rotating is implemented using AffineTransform. This works fine.
However, imagine one of the objects that has been rotated 90 degrees. Its north face will be facing east in
the viewport. When a user resizes the object by grabbing the east-side (i.e. the north handle before rotation)
resize-handle and dragging it to the east it is essentially resizing the object in a northwise direction.
This means that the height of the object is increased and that its origin (top left point) is decreased. However,
this will be drawn on screen exactly as stated: the height is increased and the origin is decreased and afterwards
the image is rotated. All this results in an object with the correct size, but drawn at the wrong location (I draw the
BufferedImage at the origin-point which was just decreased).
Might be a long and akward story, so here I will post a small example application which illustrates the behaviour
of my program. The program shows a BufferedImage. On this image a rectangle is drawn, along with an ellipse that
indicates the north face of the rectangle. Pressing 'R' results in a rotation of 90 degrees, whereas pressing any
of the four arrow-keys results in a 5-pixel increase in size. Just pressing R once and then an arrow key will
illustrate my problem.
My question is simple: how should I go about resizing (not rescaling, I really want to increase the
number of paintable pixels for my BufferedImage!) a BufferedImage that's been rotated using AffineTransform.
Any suggestions are greatly appreciated!
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
* Creates a BufferedImage that displays a simple image.
* This Image will can be rotated 1/2 PI degrees by pressing 'R'.
* By pressing any of the arrow-keys, the image is resized as if stretching
* the top of the image. (i.e. in the original, non-rotated, image it
* simply moves the origin of the image and increases the height).
public class ImageTest extends JPanel implements KeyListener
double theta = 0.0; // rotation angle
Point origin = new Point(50,50); // origin of the image
Dimension size = new Dimension(100,100); // size of the image
public static void main(String[] args)
JFrame mainFrame = new JFrame("Image Tester");
ImageTest imageTest = new ImageTest();
mainFrame.getContentPane().add(imageTest);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(400,400);
mainFrame.show();
mainFrame.addKeyListener(imageTest);
// draw the image on the JPanel
public void paintComponent(Graphics g)
super.paintComponent(g);
// create a BufferedImage and draw something on it (a rectangle)
BufferedImage image =
new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
Graphics g2 = image.createGraphics();
g2.drawRect(0, 0, size.width - 1, size.height - 1);
g2.fillOval(size.width / 2, 0, 3, 3); // draw a little 'north' indicator
g2.dispose();
// now rotate g
Graphics2D g2d = (Graphics2D)g;
g2d.rotate(theta,
origin.x + size.width / 2.0,
origin.y + size.height / 2.0);
// and draw the image on the specified origin
g2d.drawImage(image, origin.x, origin.y, null);
* @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
public void keyPressed(KeyEvent arg0)
switch(arg0.getKeyCode())
case (KeyEvent.VK_R):
// rotate! add 1 / 2 PI degrees of rotation
theta += Math.PI / 2;
repaint();
break;
case (KeyEvent.VK_LEFT):
case (KeyEvent.VK_RIGHT):
case (KeyEvent.VK_DOWN):
case (KeyEvent.VK_UP):
// make the image 5 pixels larger
origin.y = origin.y - 5;
size.height += 5;
repaint();
break;
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
public void keyReleased(KeyEvent arg0)
* @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
public void keyTyped(KeyEvent arg0)
}Thanks Olek for your suggestion.
I took your advice (kind-of) and tried something.
Now I create a BufferedImage on which I draw a rectangle. The resulting Image is transformed to a rotated version of
this image. To do so, a new BufferedImage is created based on an AffineTransformOp.
This resulting (rotated) image is then shown on screen.
However, it still does not work correctly.
I have to state that this is a very simplified version of my problem. The original program features 8 resize handles, along with one rotation handle above
the object. When no rotation has been applied everything works fine (i.e. the object can be resized using the handles). However, if someone uses
the rotation handle to rotate the object 90 degrees (for example), resizing does no longer work correctly.
This sample program that I provided intends to mimic the case in which a user is stretching a rectangle to the north (without rotation) and to the
east (with 90 degrees of rotation). As you can see, if you press the UP-arrow if the object is not rotated, it does exactly what it needs to do:
stretch to the north (i.e. update the origin and increase the height). If you press R once and then try the UP-arrow again, you see that it still does what it needs to do. However, since I update the origin, the BufferedImage is moving up.
This all is very logical and the program does exactly what I ask it to do. However, it is not what I want it to do and I do not know how to implement what I really want.
Maybe someone can sketch some solution to this problem:
1 - Display a buffered image of size 30 x 30 (with some north-indicator)
2 - Stretch this image to the north a few pixels
3 - Rotate the buffered image 90 degrees clockwise around its center (north indicator is pointing east)
4 - Stretch this image to the east a few pixels (which, I think, corresponds to the operation in 2, but it clearly does not!)
This might be the little kick I need to set me off in the right direction again. I think I might have been thinking about this too long to see the solution
myself.
Listed here is my own updated version of the sample I provided in my first post. Clockwise rotation is still key R, counter clockwise rotation is E,
stretching the image to the north is UP-arrow and decreasing the image from the north is down (i.e. up and down mimic the case in which a user uses
the northern resize-handle to resize the image; in case of rotation this northern resize-handle is obviously displayed east or whatever).
Any help is appreciated as always!
package test;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
* Creates a BufferedImage that displays a simple image.
* This Image will can be rotated 1/2 PI degrees by pressing 'R'.
* By pressing any of the arrow-keys, the image is resized as if stretching
* the top of the image. (i.e. in the original, non-rotated, image it
* simply moves the origin of the image and increases the height).
public class ImageTest extends JPanel implements KeyListener
double theta = 0.0; // rotation angle
Point origin = new Point(50,50); // origin of the image drawing
Dimension size = new Dimension(100,100); // size of the image
public static void main(String[] args)
JFrame mainFrame = new JFrame("Image Tester");
ImageTest imageTest = new ImageTest();
mainFrame.getContentPane().add(imageTest);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(400,400);
mainFrame.show();
mainFrame.addKeyListener(imageTest);
public void paintComponent(Graphics g)
super.paintComponent(g);
// get the BufferedImage in its rotated version;
BufferedImage image = getImage();
// display the image
g.drawImage(image, origin.x, origin.y, null);
private BufferedImage getImage()
BufferedImage result =
new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
// draw a nice rectangle
Graphics g = result.createGraphics();
g.fillRect(0, 0, size.width, size.height);
// and a north indicator
g.setColor(Color.BLACK);
g.fillOval(size.width / 2 - 3, 0, 6, 6);
return applyRotation(result);
private BufferedImage applyRotation(BufferedImage source)
// create the rotation
AffineTransform transform =
AffineTransform.getRotateInstance(
theta,
source.getWidth() / 2,
source.getHeight() / 2);
// make an Operation to create the new buffered image
AffineTransformOp transformOp =
new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
// create dest image
BufferedImage dest =
transformOp.createCompatibleDestImage(source, source.getColorModel());
// apply the filter
transformOp.filter(source, dest);
return dest;
* @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
public void keyPressed(KeyEvent arg0)
int key = arg0.getKeyCode();
switch(key)
case KeyEvent.VK_R:
// rotate clockwise
theta += Math.PI / 2;
break;
case KeyEvent.VK_E:
// rotate counter-clockwise
theta -= Math.PI / 2;
break;
case KeyEvent.VK_UP:
// scale up
origin.y -= 5;
size.height += 5;
break;
case KeyEvent.VK_DOWN:
// scale down
origin.y += 5;
size.height -= 5;
break;
repaint();
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
public void keyReleased(KeyEvent arg0)
* @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
public void keyTyped(KeyEvent arg0)
} -
Dealing with AffineTransform mouse driven rotation
Hi there,
I'm implementing the mouse control to navigate through an image representing a map. Pan and zoom where trivial operations, but I'm getting in trouble when trying to rotate the BufferedImage.
I actually can perform the rotation, but because the map coordinate system gets rotated too. I have applied a trigonometric correction when performing a pan after a rotation. This was the hard part... my problem is that I have inverted the axis when panning, so dragging the mouse to the bottom of the canvas becomes a horizontal translation if we had a rotation by PI rads.
Because original Java code is pretty big, I have coded a simple example that pans, zooms or rotates a square.
The magic happens here:
def performPan(self,diff):
xa = diff.x*lang.Math.cos(self.theta)+diff.y*lang.Math.sin(self.theta)
ya = -diff.x*lang.Math.sin(self.theta)+diff.y*lang.Math.cos(self.theta)
diff.x -= (diff.x - xa)
diff.y -= (diff.y - ya)
center = self.canvas.squareCenter()
# if self.theta != 0: self.transform.rotate(-self.theta, center.x, center.y)
self.transform.translate(diff.x, diff.y)
#if self.theta != 0: self.transform.rotate(self.theta, center.x, center.y)
def performZoom(self,diff):
zoomLevel = 1.0+0.01*diff.y;
if zoomLevel <= 0:
zoomLevel = 0
center = self.canvas.windowCenter()
self.transform.scale(zoomLevel, zoomLevel)
def performRotation(self,diff):
angleStep = diff.y * 0.1
self.theta += diff.y
self.theta %= 2*lang.Math.PI
center = self.canvas.squareCenter()
self.transform.rotate(angleStep, center.x, center.y)
def toWindowCoordinates(self,diff):
try:
self.transform.inverseTransform(diff,diff)
except:
print "error en window coordinates"I have already tried changing diff.x and diff.x sign, and commenting that trigonometric correction and uncommeting the lines concatenating two rotations surrounding the translation without sucess.
Please, I'd appreciate some feedback. Brainstorms are welcome. :-)
Thanks, Vicente.
The full code:
from javax import swing
from java import awt, lang;
class Listener(swing.event.MouseInputAdapter):
def __init__(self,subject):
self.offset = awt.geom.Point2D.Double()
self.anchor = awt.geom.Point2D.Double()
self.canvas = subject
self.transform = subject.transform
self.rectangle = subject.rectangle
self.theta = 0.0
def mousePressed(self,e):
self.anchor.x = e.getX()
self.anchor.y = e.getY()
self.offset.x = e.getX()
self.offset.y = e.getY()
def mouseDragged(self,e):
self.offset.x = e.getX()
self.offset.y = e.getY()
diff = awt.geom.Point2D.Double()
tx = self.offset.x - self.anchor.x
ty = self.offset.y - self.anchor.y
diff.x = tx
diff.y = ty
self.anchor.x = self.offset.x
self.anchor.y = self.offset.y
class Painter(lang.Runnable):
def __init__(self,canvas, listener):
self.canvas = canvas
self.listener = listener
def run(self):
if e.isControlDown():
self.listener.performRotation(diff)
elif swing.SwingUtilities.isLeftMouseButton(e):
self.listener.performPan(diff)
if swing.SwingUtilities.isRightMouseButton(e):
self.listener.performZoom(diff)
self.canvas.repaint()
work = Painter(self.canvas, self)
swing.SwingUtilities.invokeLater(work)
def mouseReleased(self,e):
self.color = awt.Color.red
self.canvas.repaint()
def performPan(self,diff):
xa = diff.x*lang.Math.cos(self.theta)+diff.y*lang.Math.sin(self.theta)
ya = -diff.x*lang.Math.sin(self.theta)+diff.y*lang.Math.cos(self.theta)
diff.x -= (diff.x - xa)
diff.y -= (diff.y - ya)
center = self.canvas.squareCenter()
if self.theta != 0: self.transform.rotate(-self.theta, center.x, center.y)
self.transform.translate(diff.x, diff.y)
if self.theta != 0: self.transform.rotate(self.theta, center.x, center.y)
def performZoom(self,diff):
zoomLevel = 1.0+0.01*diff.y;
if zoomLevel <= 0:
zoomLevel = 0
center = self.canvas.windowCenter()
self.transform.scale(zoomLevel, zoomLevel)
def performRotation(self,diff):
angleStep = diff.y * 0.1
self.theta += diff.y
self.theta %= 2*lang.Math.PI
center = self.canvas.squareCenter()
self.transform.rotate(angleStep, center.x, center.y)
def toWindowCoordinates(self,diff):
try:
self.transform.inverseTransform(diff,diff)
except:
print "error en window coordinates"
class Canvas(swing.JPanel):
def __init__(self):
self.rectangle = awt.geom.Rectangle2D.Double(0,0,50,50)
self.transform = awt.geom.AffineTransform()
self.wcenter = awt.geom.Point2D.Double()
self.rcenter = awt.geom.Point2D.Double()
listener = Listener(self)
swing.JPanel.addMouseMotionListener(self,listener)
swing.JPanel.addMouseListener(self,listener)
def paintComponent(self,g2d):
self.super__paintComponent(g2d)
g2d.setTransform(self.transform)
g2d.fill(self.rectangle)
def windowCenter(self):
if self.wcenter.x == 0 or self.wcenter.y == 0:
self.wcenter.x = self.getHeight()/2.0
self.wcenter.y = self.getWidth()/2.0
return self.wcenter
def squareCenter(self):
if self.rcenter.x == 0 or self.rcenter.y == 0:
self.rcenter.x = self.rectangle.getBounds2D().height/2.0
self.rcenter.y = self.rectangle.getBounds2D().width/2.0
return self.rcenter
frame = swing.JFrame( title="test",
visible=1,
defaultCloseOperation = swing.JFrame.EXIT_ON_CLOSE,
preferredSize = awt.Dimension(400,400),
maximumSize = awt.Dimension(800,600),
minimumSize = awt.Dimension(200,200),
size = awt.Dimension(500,500)
frame.add(Canvas(), awt.BorderLayout.CENTER)
frame.pack()I forgot to mention that the example is written in
Jython, because the Java was pretty big, but it is
legible bu a Java programmer. :-)It's legible, but most of us w/out a jython compiler would have to re-write the code if we wanted to try it out. That may hurt your chances of getting a useful response (as opposed to my useless responses). ... Or it might not.
Good luck!
/Pete -
3D Rotating on it's own center axis problem...
Need some help here. This is my first time using 3D in flash.
I have a movieclip (picture 80 x 80 pix) that I am tweening to look like it is rotating like face of a cube.
What I did:
1. I transformed the z-axis to "raise" the picture off of the y axis.
2. Then I rotated it around the y-axis from one end of my tween to the other.
Looks great when I scroll through the movie clip's time line but (starts on right almost paper thing, rotates to center square, and continues to the left again paper thin) The problem is when I place it on the stage and preview the swf, it rotates around its own center point and not the offset y-axis.
If I convert it to frame by frame animation, it works but I don't want to do that.
Please advise someone.
Thanks!Sorry if I don't' quite get it, but my other thread was about the movieclip defaulting to the stages coordinates. In this case my movieclip's animation is rotating around the symbols center point and not around the y-axis as I would like.
I can move the transform the symbol from axis point to another and it is fine but in this case i am only rotating it but after I placed is away from the y-axies. I expect it to "orbit" around the y axis continually facing it...and it does when I move through the tweaned frames, but when I publish the swf, it no longer "orbits" around the y-axis but rather just spins around it's center point.
I hope this is a little clearer, and thanks for your other answer. I'll plug that code in as soon as I can. -
How to make shape rotation at it's center point?
I draw a shape,like follows:
var shape1:Shape;
shape1=draw();
addChild(shape1);
shape1.rotation=50;
private function draw():Shape{
var shape:Shape = new Shape();
shape.graphics.beginFill(0x00FFFF);
shape.graphics.moveTo(200,200);
shape.graphics.lineTo(300, 202);
shape.graphics.lineTo(200, 204);
shape.graphics.lineTo(100, 202);
shape.graphics.lineTo(200, 200);
return shape;
Then I want to rotate the shape at it's center point(200,202) by using shape1.rotation=50,but I find the shape don't rotate at the the center of it's shape. How to realize the function which make shape rotate at its center point?
ThanksHere is a sample to make it rotate from center:
var sprite:Sprite=new Sprite();
sprite.graphics.lineStyle(3,0x00ff00);
sprite.graphics.beginFill(0x0000FF);
sprite.graphics.moveTo(0,0);
sprite.graphics.lineTo(100,0);
sprite.graphics.lineTo(100,100);
sprite.graphics.lineTo(0,100);
sprite.graphics.lineTo(0,0);
sprite.graphics.endFill();
var mc:Sprite=new Sprite();
mc.addChild(sprite);
//This will make the sprite to center
mc.getChildAt(0).x=-(mc.getChildAt(0).width/2);
mc.getChildAt(0).y=-(mc.getChildAt(0).height/2);
addChild(mc);
mc.x=200;
mc.y=300;
//Now it rotates from the center.
mc.rotation=20; -
Rotating entire JFrame to simulate portrait mode
Hi
I need to rotate the entire jframe into portrait mode.
I cannot use the graphics chip, or linux graphics device manger to change the rotation CW 90 degress - due to hardware design and limitation.
So basically, I have to render the graphics myself, quite easily done with fllowing code at the the top level panel.
protected void paintComponent(Graphics g)
// center of rotation is center of the panel
Graphics2D g2d =(Graphics2D)g;
int xRot = this.getWidth() / 2;
int yRot = this.getHeight() / 2;
g2d.rotate(Math.toRadians(-90), xRot, yRot);
super.paintComponent(g);
This does the job nicely, however the screen is still using landscape co-ordinates, and hence when clicking on the swing components they are in the pre-rotation position.
I have looked and cannot find, is there a simple way to switch a jframe into portrait mode. If not, is there a simple way to intercept the screen coordinates and translate the mouse coordinates to the appropriate JComponent?
thanks in advance
Steveimport java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class TransformPoints extends JPanel {
List<PointStore> list = new ArrayList<PointStore>();
AffineTransform at = new AffineTransform();
String s = "Hello World";
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Color color = g2.getColor();
drawPoints(g2);
g2.setPaint(color);
FontRenderContext frc = g2.getFontRenderContext();
Font font = g2.getFont().deriveFont(36f);
Graphics2D copy = (Graphics2D)g.create();
copy.setFont(font);
LineMetrics lm = font.getLineMetrics(s, frc);
float height = lm.getAscent() + lm.getDescent();
float width = (float)font.getStringBounds(s, frc).getWidth();
int w = getWidth();
int h = getHeight();
System.out.printf("w: %d h: %d%n", w, h);
float x = (w - width)/2;
float y = (h - height)/2 + lm.getAscent();
// copy.rotate(-Math.PI/2, w/2, h/2);
at.setToRotation(-Math.PI/2, w/2, h/2);
copy.transform(at);
copy.drawString(s, x, y);
// draw some reference lines
copy.setPaint(Color.pink);
copy.draw(getBounds());
copy.drawLine(w/2, 0, w/2, h);
copy.drawLine(0, h/2, w, h/2);
copy.dispose();
private void drawPoints(Graphics2D g2) {
for(int i = 0; i < list.size(); i++) {
PointStore store = list.get(i);
Point p = store.loc;
g2.setPaint(Color.blue);
g2.drawString(store.viewLoc, p.x+3, p.y);
g2.setPaint(Color.red);
g2.drawString(store.xformLoc, p.x+3, p.y+12);
g2.fill(new Ellipse2D.Double(p.x-1.5, p.y-1.5, 4, 4));
public static void main(String[] args) {
TransformPoints test = new TransformPoints();
JFrame f = new JFrame("click me");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(test);
f.setSize(500,300);
f.setLocation(100,100);
f.setVisible(true);
test.addMouseListener(test.ml);
private MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
String viewStr = String.format("[%d, %d]", p.x, p.y);
Point2D.Double xp = getInvertedPoint(p);
String xfStr = String.format("[%.1f, %.1f]", xp.x, xp.y);
list.add(new PointStore(p, viewStr, xfStr));
repaint();
private Point2D.Double getInvertedPoint(Point2D p) {
Point2D.Double xp = new Point2D.Double();
if(at.getDeterminant() != 0) {
try {
at.inverseTransform(p, xp);
} catch(NoninvertibleTransformException e) {
System.out.println("invert error: " + e.getMessage());
return xp;
class PointStore {
Point loc;
String viewLoc;
String xformLoc;
public PointStore(Point p, String view, String xform) {
loc = p;
viewLoc = view;
xformLoc = xform;
} -
Need help with the rotate and zoom button...
hi, i create a Jpanel code that use for zoom in and rotate image, the rotate button work fine but the zoom in is not work by the following code, can any one tell me how to fix this?
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import javax.swing.event.*;
public class RotatePanel extends JPanel {
private double m_zoom = 1.0;
private double m_zoomPercentage;
private Image image;
private double currentAngle;
private Button rotate1, rotate2, rotate3,zoom;
public RotatePanel(Image image) {
this.image = image;
MediaTracker mt = new MediaTracker(this);
mt.addImage(image, 0);
try {
mt.waitForID(0);
catch (Exception e) {
e.printStackTrace();
public void rotate() {
//rotate 5 degrees at a time
currentAngle+=90.0;
if (currentAngle >= 360.0) {
currentAngle = 0;
repaint();
public void setZoomPercentage(int zoomPercentage)
m_zoomPercentage = ((double)zoomPercentage) / 100;
public void originalSize()
m_zoom = 1;
public void zoomIn()
m_zoom += m_zoomPercentage;
public void zoomOut()
m_zoom -= m_zoomPercentage;
if(m_zoom < m_zoomPercentage)
if(m_zoomPercentage > 1.0)
m_zoom = 1.0;
else
zoomIn();
public double getZoomedTo()
return m_zoom * 100;
public void rotate1() {
//rotate 5 degrees at a time
currentAngle+=180.0;
if (currentAngle >= 360.0) {
currentAngle = 0;
repaint();
public void rotate2() {
//rotate 5 degrees at a time
currentAngle+=270.0;
if (currentAngle >= 360.0) {
currentAngle = 0;
repaint();
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
AffineTransform origXform = g2d.getTransform();
AffineTransform newXform = (AffineTransform)(origXform.clone());
//center of rotation is center of the panel
int xRot = this.getWidth()/2;
int yRot = this.getHeight()/2;
newXform.rotate(Math.toRadians(currentAngle), xRot, yRot);
g2d.setTransform(newXform);
//draw image centered in panel
int x = (getWidth() - image.getWidth(this))/2;
int y = (getHeight() - image.getHeight(this))/2;
g2d.scale(m_zoom, m_zoom);
g2d.drawImage(image, x, y, this);
g2d.setTransform(origXform);
public Dimension getPreferredSize() {
return new Dimension((int)(image.getWidth(this) +
(image.getWidth(this) * (m_zoom - 1))),
(int)(image.getHeight(this) +
(image.getHeight(this) * (m_zoom -1 ))));
public static void main(String[] args) throws IOException{
JFrame f = new JFrame();
Container cp = f.getContentPane();
cp.setLayout(new BorderLayout());
Image testImage =
Toolkit.getDefaultToolkit().getImage("clouds.jpg");
final RotatePanel rotatePanel = new RotatePanel(testImage);
final RotatePanel zomePanel = new RotatePanel(testImage);
JButton b = new JButton ("90 degree");
JButton c = new JButton ("180 degree");
JButton d = new JButton ("270 degree");
JButton e = new JButton ("zoom in");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
rotatePanel.rotate1();
d.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
rotatePanel.rotate2();
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
rotatePanel.rotate();
e.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
zomePanel.zoomIn();
cp.add(rotatePanel, BorderLayout.NORTH);
cp.add(b, BorderLayout.WEST);
cp.add(c, BorderLayout.CENTER);
cp.add(d, BorderLayout.EAST);
cp.add(e, BorderLayout.SOUTH);
// f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,500);
f.setVisible(true);
}TRIPLE CROSS POSTED
[_http://forum.java.sun.com/thread.jspa?threadID=5314687&messageID=10342105#10342105_|http://forum.java.sun.com/thread.jspa?threadID=5314687&messageID=10342105#10342105]
Stop posting this question over and over in multiple forums please.
Maybe you are looking for
-
Copy and Paste a channel in Photoshop CC
Following an on line tutorial I need to copy one channel of an image layer then paste it to the RGB channel. Command C/V does not work while it does in the tutorial. I am not sure what version Photoshop is being used the tutorial, but I have seen o
-
perspective transformation is still not working well: when applying an vertical or horizontal correction the image slides out of the frame, leaving an gray border at the other side. with scaling you can get the content back, but you loose resolution
-
Question mark over the Mail icon
What can I do if there is a question mark over the mail icon in dock... I can't open the Mail now. Thanks!
-
Screen level validation on xk01 with holding tax screen .
Hi, Can someone suggest a suitable way by which I can do screen level validation on xk01 screen 610,so that in case of user not giving proper inputas the concerned field is open for user input . Right now I am using an exit but it is triggered afete
-
Re:How to pick the date format as dd/MM/yyyy from the database
Hi all, I am using JDev 11.1.2.3.0 My requirement is ,i want to pick the date from the database as dd/MM/yyyy format.I set the attribute as r1.setAttribute("JobDescription", "From" + olrow.getAttribute("PeriodFrom") + "To" + olrow.getAttribute("Perio