I want to rotate image with some angle as show in the below image.
I am trying to with that
CGAffineTransform t = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(degrees));
imageView.transform = t;
I am not getting output like this. even I am not close with this.
Here is the code I used to rotate an image by 30 degrees
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20, 320, 400)];
imgView.image = [UIImage imageNamed:#"maxresdefault.jpg"];
[self.view addSubview:imgView];
float degrees = 30.0f;
float radians = (degrees* M_PI/180);
imgView.layer.transform = CATransform3DMakeRotation(radians, 0, 0, 1.0);
The Simulator ScreenShot before transform
Here is the Simulator ScreenShot after Transform
Hope this helps you out.
Reset by transform before apply other transforms...
imageView.transform = CGAffineTransformIdentity
// i hope your angle is proper calculate
CGAffineTransform t = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(degrees));
imageView.transform = t;
Hope it will help you
You can change the layer.transform like below in swift
imageView?.layer.transform = CATransform3DMakeAffineTransform(CGAffineTransform(rotationAngle: CGFloat(M_PI_2)))
For Objective C :
imageView.layer.transform = CATransform3DMakeAffineTransform(CGAffineTransformMakeRotation(M_PI_2));
Related
How can I create progressView with width 100 and height 200. And rotate progressView on 90 degrees?
It does not work together.
Or progressView is turned by 90 or change size
self.progressView.transform = CGAffineTransformMakeRotation(M_PI_2);
CGAffineTransform transform = CGAffineTransformMakeScale(1.0f, 3.0f);
_progressView.transform = transform;
You need to chain your transformations. In your sample, the 2nd assignment to transform effectively overwrites the first one. This one works:
UIProgressView *progressBar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
progressBar.frame = CGRectMake(50, 100, 100, 50);
CGAffineTransform t = CGAffineTransformMakeRotation(M_PI_2);
t = CGAffineTransformScale(t, 1.0f, 50.0f);
progressBar.transform = t;
[self.view addSubview:progressBar];
I read about that somewhere...I think CGAffineTransform() works for that
[self.progressView setTransform:CGAffineTransformMakeScale(1.0, 2.0)];
For rotation
#define DEGREES_TO_RADIANS(angle) ((90) / 180.0 * M_PI)
[self.progressView setTransform:CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(angle))];
Swift 4
progressView.transform = CGAffineTransform(scaleX: 1.0, y: 2.0)
I am trying to create a custom animation something like the default flip animation for a UIView, but without the actual flip, and also the axis of the flip I want to be on the left side not on the center. Here is an example of what I am trying to accomplish but without the repeat:
Also in the code I will add UILabel as sub view and a few more elements.
If you can provide a code example it will be much appreciated
Thank you very much in advance for any support!
Update:
used the example provided by #artal and obtained the wanted effect for UIImageView but how can I obtain the same example for an UIButton?
Tried the next code:
objectivesButton = [[UIButton alloc] initWithFrame:CGRectMake( 0.25f * [UIScreen mainScreen].bounds.size.width, 0.7f * [UIScreen mainScreen].bounds.size.height, 0.5f * [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height * 0.3f)];
[objectivesButton addTarget:self
action:#selector(startAnimationButton)
forControlEvents:UIControlEventTouchUpInside];
objectivesButton.backgroundColor = [UIColor yellowColor];
objectivesButton.layer.anchorPoint = CGPointMake(0, 0.5);
[self.view addSubview:objectivesButton];
- (void)startAnimationButton{
CATransform3D perspectiveTrasnform = CATransform3DIdentity;
perspectiveTrasnform.m34 = -0.004;
CGFloat rotateAngleDeg = 90;
CATransform3D flipTransform = CATransform3DRotate(perspectiveTrasnform, rotateAngleDeg / 180.0 * M_PI, 0, 1.5, 0);
[UIView animateWithDuration:3.0f animations:^()
{
objectivesButton.layer.transform = flipTransform;
}];
}
You can animate the view this way by applying a perspective and rotation transform to its underlying CALayer (a 3D transform).
To start it from the left side you can set the anchorPoint of the layer.
Here's an example:
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"image.png"]];
imageView.center = CGPointMake(self.view.center.x - imageView.frame.size.width * 0.5, self.view.center.y + imageView.frame.size.height * 0.5);
imageView.layer.anchorPoint = CGPointMake(0, 1);
[self.view addSubview:imageView];
CATransform3D perspectiveTrasnform = CATransform3DIdentity;
perspectiveTrasnform.m34 = -0.004;
CGFloat rotateAngleDeg = 90;
CATransform3D flipTransform = CATransform3DRotate(perspectiveTrasnform, rotateAngleDeg / 180.0 * M_PI, 0, 1, 0);
[UIView animateWithDuration:5 animations:^()
{
imageView.layer.transform = flipTransform;
}];
I'm re-introducing myself to iOS programming and am running into a seemingly simple problem. I have been following this example about how to rotate a image according to the user's heading. The crucial part is:
float heading = -1.0f * M_PI * newHeading.magneticHeading / 180.0f;
arrowImage.transform = CGAffineTransformMakeRotation(heading);
The image is indeed rotated but the center doesn't seem to be the anchor point for the rotation. I've been googling but can't figure it out. Could someone point me in the right direction?
Here's a screenshot in case it isn't clear: in the initial state, the label is centered in the circle and the white square is centered in the image:
This code works for my:
UIImage *img = [UIImage imageNamed:#"Image.png"];
UIImageView *imageToMove = [[UIImageView alloc] initWithImage:img];
CATransform3D rotationTransform = CATransform3DMakeRotation(1.0f * M_PI, 0, 0, 1.0);
CABasicAnimation* rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:#"transform"];
rotationAnimation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
rotationAnimation.duration = 0.6f;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = FLT_MAX;
[imageToMove.layer addAnimation:rotationAnimation forKey:#"rotationAnimation"];
[self.view addSubview:imageToMove];
Swift port of Greg's code
let rotationTransform: CATransform3D = CATransform3DMakeRotation(.pi, 0, 0, 1.0);
let rotationAnimation = CABasicAnimation(keyPath: "transform");
rotationAnimation.toValue = NSValue(caTransform3D: rotationTransform)
rotationAnimation.duration = 0.6;
rotationAnimation.isCumulative = true;
rotationAnimation.repeatCount = Float.infinity;
progressArc.layer.add(rotationAnimation, forKey:"rotationAnimation")
try this code for your case
var angle=0;
self.btnImage.center=CGPointMake(self.btnImage.center.x, self.btnImage.center.y);
self.btnImage.transform=CGAffineTransformMakeRotation (angle);
angle+=0.15;
keep the above one into method, use the time interval or call the method when ever you want to change the angle of the image.
I need to rotate my UIImageView, or the UIImage in the UIImageView, while moving its frame with NSTimer. This is the NSTimer movement :
timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:#selector(animate) userInfo:nil repeats:YES];
This is the animate method (a part of it, the most important) :
CGRect viewLocation = [[[self layer] presentationLayer] frame];
self.frame = CGRectMake(viewLocation.origin.x, viewLocation.origin.y + 0.2, viewLocation.size.width, viewLocation.size.height);
And this is the method i'm trying to use to rotate the UIImage :
- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees
{
// calculate the size of the rotated view's containing box for our drawing space
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)];
CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
rotatedViewBox.transform = t;
CGSize rotatedSize = rotatedViewBox.frame.size;
[rotatedViewBox release];
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext();
// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
// Rotate the image context
CGContextRotateCTM(bitmap, DegreesToRadians(degrees));
// Now, draw the rotated/scaled image into the context
CGContextScaleCTM(bitmap, 1.0, -1.0);
CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
This code is inside a subclass of UIImageView, so self is referred to UIImageView.
I also try to rotate UIImageView with CGAffineTransform, but the UIImageView is being stretched and rotate in a strange manner.
This is the method :
- (void)rotateWithDegrees:(CGFloat)degrees {
CGAffineTransform transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(degrees));
self.transform = transform;
}
And this is the macro :
#define DEGREES_TO_RADIANS(angle) (angle / 180.0 * M_PI)
The important thing is that you can always use the timer to move the object, so that part is unchangeable.
I found the solution! First of all we exclude the solution that provides the resize of UIImage. So, we rotate the UIImageView, but when use CGAffineTransform the frame have NOT to be modified! So, to move the UIImageView with the timer we have to modify the center of the UIImageView. This is to delete :
CGRect viewLocation = [[[self layer] presentationLayer] frame];
self.frame = CGRectMake(viewLocation.origin.x, viewLocation.origin.y + 0.2, viewLocation.size.width, viewLocation.size.height);
And this is to add :
self.center = CGPointMake(self.frame.origin.x + (self.frame.size.width / 2), self.frame.origin.y + 0.2 + (self.frame.size.height / 2));
Then, we can use the rotateWithDegrees: method to rotate the UIImageView :
- (void)rotateWithDegrees:(CGFloat)degrees {
CGAffineTransform transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(degrees));
self.transform = transform;
_degrees+=0.5;
if (_degrees == 360) {
_degrees = 1;
}
}
So, we can add the line :
[self rotateWithDegrees:_degrees];
below :
self.center = CGPointMake(self.frame.origin.x + (self.frame.size.width / 2), self.frame.origin.y + 0.2 + (self.frame.size.height / 2));
The UIImageView moves due to the change of its center, and not due to the change of its frame and this allow to use CGAffineTransform for the rotation.
Please give ideas for how to crop UIImage on oval shape or circle shape. Please share your ideas.
#import <QuartzCore/QuartzCore.h>
CALayer *imageLayer = YourImageview.layer;
[imageLayer setCornerRadius:5];
[imageLayer setBorderWidth:1];
[imageLayer setMasksToBounds:YES];
by increasing radius it will become more round-able.
As long as the image is a square, you can get a perfect circle by taking half the width as the corner radius:
[imageView.layer setCornerRadius:imageView.frame.size.width/2];
You also need to add
[imageView.layer setMasksToBounds:YES];
Swift 4.2
import QuartzCore
var imageLayer: CALayer? = YourImageview.layer
imageLayer?.cornerRadius = 5
imageLayer?.borderWidth = 1
imageLayer?.masksToBounds = true
I started looking into this a couple of weeks back. I tried all the suggestions here, none of which worked well. In the great tradition of RTFM I went and read Apple's documentation on Quartz 2D Programming and came up with this. Please try it out and let me know how you go.
The code could be fairly easily altered to crop to an elipse, or any other shape defined by a path.
Make sure you include Quartz 2D in your project.
#include <math.h>
+ (UIImage*)circularScaleAndCropImage:(UIImage*)image frame:(CGRect)frame {
// This function returns a newImage, based on image, that has been:
// - scaled to fit in (CGRect) rect
// - and cropped within a circle of radius: rectWidth/2
//Create the bitmap graphics context
UIGraphicsBeginImageContextWithOptions(CGSizeMake(frame.size.width, frame.size.height), NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
//Get the width and heights
CGFloat imageWidth = image.size.width;
CGFloat imageHeight = image.size.height;
CGFloat rectWidth = frame.size.width;
CGFloat rectHeight = frame.size.height;
//Calculate the scale factor
CGFloat scaleFactorX = rectWidth/imageWidth;
CGFloat scaleFactorY = rectHeight/imageHeight;
//Calculate the centre of the circle
CGFloat imageCentreX = rectWidth/2;
CGFloat imageCentreY = rectHeight/2;
// Create and CLIP to a CIRCULAR Path
// (This could be replaced with any closed path if you want a different shaped clip)
CGFloat radius = rectWidth/2;
CGContextBeginPath (context);
CGContextAddArc (context, imageCentreX, imageCentreY, radius, 0, 2*M_PI, 0);
CGContextClosePath (context);
CGContextClip (context);
//Set the SCALE factor for the graphics context
//All future draw calls will be scaled by this factor
CGContextScaleCTM (context, scaleFactorX, scaleFactorY);
// Draw the IMAGE
CGRect myRect = CGRectMake(0, 0, imageWidth, imageHeight);
[image drawInRect:myRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Include the following code in your UIView class replacing "monk2.png" with your own image name.
- (void)drawRect:(CGRect)rect {
UIImage *originalImage = [UIImage imageNamed:[NSString stringWithFormat:#"monk2.png"]];
CGFloat oImageWidth = originalImage.size.width;
CGFloat oImageHeight = originalImage.size.height;
// Draw the original image at the origin
CGRect oRect = CGRectMake(0, 0, oImageWidth, oImageHeight);
[originalImage drawInRect:oRect];
// Set the newRect to half the size of the original image
CGRect newRect = CGRectMake(0, 0, oImageWidth/2, oImageHeight/2);
UIImage *newImage = [self circularScaleAndCropImage:originalImage frame:newRect];
CGFloat nImageWidth = newImage.size.width;
CGFloat nImageHeight = newImage.size.height;
//Draw the scaled and cropped image
CGRect thisRect = CGRectMake(oImageWidth+10, 0, nImageWidth, nImageHeight);
[newImage drawInRect:thisRect];
}
To have imageView in oval shape is not difficult.
You can do the following
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:yourImageView.bounds];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = path.CGPath;
yourImageView.layer.mask = maskLayer;
If the rect passed to bezierPathWithOvalInRect is Square the image will be cropped to circle.
Swift Code
let path = UIBezierPath(ovalIn: yourImageView.bounds)
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
yourImageView.layer.mask = maskLayer
To make a RoundShape Image
Step1: in .h file
#property (strong, nonatomic) IBOutlet UIImageView *songImage;
Step2: in .m file
- (void)viewDidLoad
{
self.songImage.layer.cornerRadius = self.songImage.frame.size.width / 2;
self.songImage.clipsToBounds = YES;
//To give the Border and Border color of imageview
self.songImage.layer.borderWidth = 1.0f;
self.songImage.layer.borderColor = [UIColor colorWithRed:249/255.0f green:117/255.0f blue:44/255.0f alpha:1.0f].CGColor;
}
OR For Swift
cell.songImage.layer.cornerRadius = cell.songImage.frame.size.width / 2;
cell.songImage.clipsToBounds = true
//To give the Border and Border color of imageview
cell.songImage.layer.borderWidth = 1.0
cell.songImage.layer.borderColor = UIColor(red: 50.0/255, green: 150.0/255, blue: 65.0/255, alpha: 1.0).CGColor
After a long search I found the correct way to circle the image
Download the Support archive file from URL http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/
#import "UIImage+RoundedCorner.h"
#import "UIImage+Resize.h"
Following lines used to resize the image and convert in to round with radius
UIImage *mask = [UIImage imageNamed:#"mask.jpg"];
mask = [mask resizedImage:CGSizeMake(47, 47) interpolationQuality:kCGInterpolationHigh ];
mask = [mask roundedCornerImage:23.5 borderSize:1];
SWIFT
var vwImage = UIImageView(image: UIImage(named: "Btn_PinIt_Normal.png"))
vwImage.frame = CGRectMake(0, 0, 100, 100)
vwImage.layer.cornerRadius = vwImage.frame.size.width/2
If you only need a perfect circle, changing the shape of the UIImageView could help.
Simply add the QuartzCore framework to your project and add these lines of code somewhere in the lifecycle before the imageView is displayed:
#import <QuartzCore/QuartzCore.h>
.
.
.
//to crop your UIImageView to show only a circle
yourImageView.layer.cornerRadius = yourImageView.frame.size.width/2;
yourImageView.clipsToBounds = YES;
Check out CGImageCreateWithMask. Create a mask of your oval shape, then apply it to the image.
you should refer This ...
// Create the image from a png file
UIImage *image = [UIImage imageNamed:#"prgBinary.jpg"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// Get size of current image
CGSize size = [image size];
// Frame location in view to show original image
[imageView setFrame:CGRectMake(0, 0, size.width, size.height)];
[[self view] addSubview:imageView];
[imageView release];
// Create rectangle that represents a cropped image
// from the middle of the existing image
CGRect rect = CGRectMake(size.width / 4, size.height / 4 ,
(size.width / 2), (size.height / 2)); //oval logic goes here
// Create bitmap image from original image data,
// using rectangle to specify desired crop area
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *img = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
// Create and show the new image from bitmap data
imageView = [[UIImageView alloc] initWithImage:img];
[imageView setFrame:CGRectMake(0, 200, (size.width / 2), (size.height / 2))];
[[self view] addSubview:imageView];
[imageView release];
SWIFT 3 answer comes from #Mohammad Sadiq
let path = UIBezierPath.init(ovalIn: workingImgaeView.bounds)
let maskLayer = CAShapeLayer(layer: layer)
maskLayer.path = path.cgPath
workingImgaeView.layer.mask = maskLayer
This should work,
Try pasting below code in viewDidLoad().
self.myImage.layer.cornerRadius = self.myImage.frame.size.width / 2;
self.myImage.clipsToBounds = YES;