I have two sliders - one for changing image size and one for rotating this image. My imageview is 60x60. The problem is that I rotate the image using CGAffineTransformMakeRotation, but when I try to resize it after that (like, from 60x60 to 65x65 using the slider), it acts weirdly - the frame of the image view has changed like 80x2. How can I avoid this? Here is my code for the slider that resizes the image:
-(IBAction)imageSliderAction:(UISlider *)sender
{
NSUInteger value = sender.value;
float oldCenterX = logoImageView.center.x;
float oldCenterY = logoImageView.center.y;
newWidth = value;
newHeight = value;
CGRect frame = [logoImageView frame];
frame.size.width = newWidth;
frame.size.height = newHeight;
[logoImageView setFrame:frame];
logoImageView.center = CGPointMake(oldCenterX, oldCenterY);
}
And here is the code for my rotating slider:
-(IBAction)rotationSliderAction:(UISlider *)sender
{
NSUInteger angle = sender.value;
if (sender.value >= 1)
{
CGAffineTransform rotate = CGAffineTransformMakeRotation(angle / 180.0 * 3.14);
[logoImageView setTransform:rotate];
}
if (sender.value <= 0 )
{
CGAffineTransform rotate = CGAffineTransformMakeRotation( (360 + sender.value) / 180.0 * 3.14);
[logoImageView setTransform:rotate];
}
}
How can I avoid autochanging frame's width and height when rotating? Because after that I can't resize the image correctly.
From UIView reference
Warning: If the transform property is not the identity transform, the
value of this property is undefined and therefore should be ignored.
If you want to change the size of view that has nontrivial transform you should do that by changing its bounds property (view's center will remain the same so you won't need any extra logic to maintain its position):
[logoImageView setBounds:CGRectMake(0,0,sender.value, sender.value)];
Related
I need to create a UICollectionView like the following picture.
I have been able to make horizontally scrollable, but unable to make the UI like the picture. Any help? Thanks.
Here is what you wanted,you just need to have a custom UICollectionViewFlowLayout,and override the method -(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect to change the cell display attributes.
Here is the layout code with comment in each main operation
#implementation HorizonSclaeLayout
-(instancetype)init{
self = [super init];
if (self) {
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
}
return self;
}
static const CGFloat kMaxDistancePercentage = 0.3f;
static const CGFloat kMaxRotation = 0;//(CGFloat)(70.0 * (M_PI / 180.0));
static const CGFloat kMaxZoom = 0.6f;
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
//1 the visible rectangle of the collection view, calculated using the content offset of the view and the bounds size.
CGRect visibleRect = (CGRect){
.origin = self.collectionView.contentOffset,
.size = self.collectionView.bounds.size
};
//2 the maximum distance away from the center, which defines the distance from the center at which each cell is fully rotated
CGFloat maxDistance = visibleRect.size.width/2;
NSArray *array = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes *attributes in array) {
//3 find the distance of the cell from the center of the current visible rectangle
CGFloat distance = CGRectGetMidX(visibleRect) - attributes.center.x;
//4 normalize this distance against the maximum distance to give a percentage of how far the view is along the line from the center to the maximum points in either direction
CGFloat normalizedDistance = distance / maxDistance;
normalizedDistance = MIN(normalizedDistance, 1.0f);
normalizedDistance = MAX(normalizedDistance, -1.0f);
//5 calculate the rotation and zoom
CGFloat rotation = normalizedDistance * kMaxRotation;
CGFloat zoom = 1.0f + ((1.0f - ABS(normalizedDistance))*kMaxZoom);
//6 create the required transform by first setting m34 so that when the rotation is done
// skew is applied to make it have the appearance of coming out of and going into the screen
CATransform3D transform = CATransform3DIdentity;
transform.m34 = - 1.0 / 550.0;
transform = CATransform3DRotate(transform, rotation, 0.0f, 1.0f, 0.0f);
transform = CATransform3DScale(transform, zoom, zoom, 0.0f);
attributes.transform3D = transform;
}
return array;
}
-(CGSize)itemSize{
return CGSizeMake(60, 60 * 1.2);
}
-(CGFloat)minimumLineSpacing{
return 30;
}
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
return YES;
}
#end
Here in this sample LineLayout has already implemented the required custom layout (that's what I guessed from the image shown).
I am using SVGKit to draw a map, and it basically use SVG data to form a UIBezierPath, and pass it to CAShapeLayer and render it.
important code:
for (FSSVGPathElement* path in _svg.paths) {
// Make the map fits inside the frame
float scaleHorizontal = self.frame.size.width / _svg.bounds.size.width;
float scaleVertical = self.frame.size.height / _svg.bounds.size.height;
float scale = MIN(scaleHorizontal, scaleVertical);
CGAffineTransform scaleTransform = CGAffineTransformIdentity;
scaleTransform = CGAffineTransformMakeScale(scale, scale);
scaleTransform = CGAffineTransformTranslate(scaleTransform,-_svg.bounds.origin.x, -_svg.bounds.origin.y);
UIBezierPath* scaled = [path.path copy];
[scaled applyTransform:scaleTransform];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = scaled.CGPath;
[self.layer addSublayer:shapeLayer];
[_scaledPaths addObject:scaled];
}
The mapView's frame is set as the screen's width and height, and I found the map view's height is less than the screen height. So I want to cut the mapView's height to just same as the actual height of the map (UIBezierPah)
Because I don't know where to read the largest Y data for the UIBezierPath, I don't know how to calculate the max Y.
Can somebody help?
There is a bounds property for UIBezierPath, but what I am asking is the actual size of all the UIBeizerPath together.
I figured out with below code:
first add a property as the actual size,
#property (nonatomic, assign) CGSize actualSize;
and When handling the UIBezierPath:
for (FSSVGPathElement* path in _svg.paths) {
UIBezierPath* scaled = [path.path copy];
[scaled applyTransform:scaleTransform];
CGFloat absoluteWidth = scaled.bounds.origin.x + scaled.bounds.size.width;
CGFloat absoluteHeight = scaled.bounds.origin.y + scaled.bounds.size.height;
if (absoluteHeight > maxHeight)
maxHeight = absoluteHeight;
if (absoluteWidth > maxWidth)
maxWidth = absoluteWidth;
....
}
self.actualSize = CGSizeMake(ceil(maxWidth), ceil(maxHeight));
Now I can get the actual size after all paths are added into the CAShapeLayer.
Through this question and answer I've now got a working means of detecting when an arbitrarily rotated image isn't completely outside a cropping rect.
The next step is to figure out how to correctly adjust it's containing scroll view zoom to ensure that there are no empty spaces inside the cropping rect. To clarify, I want to enlarge (zoom in) the image; the crop rect should remain un-transformed.
The layout hierarchy looks like this:
containing UIScrollView
UIImageView (this gets arbitrarily rotated)
crop rect overlay view
... where the UIImageView can also be zoomed and panned inside the scrollView.
There are 4 gesture events that occur that need to be accounted for:
Pan gesture (done): accomplished by detecting if it's been panned incorrectly and resets the contentOffset.
Rotation CGAffineTransform
Scroll view zoom
Adjustment of the cropping rect overlay frame
As far as I can tell, I should be able to use the same logic for 2, 3, and 4 to adjust the zoomScale of the scroll view to make the image fit properly.
How do I properly calculate the zoom ratio necessary to make the rotated image fit perfectly inside the crop rect?
To better illustrate what I'm trying to accomplish, here's an example of the incorrect size:
I need to calculate the zoom ratio necessary to make it look like this:
Here's the code I've got so far using Oluseyi's solution below. It works when the rotation angle is minor (e.g. less than 1 radian), but anything over that and it goes really wonky.
CGRect visibleRect = [_scrollView convertRect:_scrollView.bounds toView:_imageView];
CGRect cropRect = _cropRectView.frame;
CGFloat rotationAngle = fabs(self.rotationAngle);
CGFloat a = visibleRect.size.height * sinf(rotationAngle);
CGFloat b = visibleRect.size.width * cosf(rotationAngle);
CGFloat c = visibleRect.size.height * cosf(rotationAngle);
CGFloat d = visibleRect.size.width * sinf(rotationAngle);
CGFloat zoomDiff = MAX(cropRect.size.width / (a + b), cropRect.size.height / (c + d));
CGFloat newZoomScale = (zoomDiff > 1) ? zoomDiff : 1.0 / zoomDiff;
[UIView animateWithDuration:0.2
delay:0.05
options:NO
animations:^{
[self centerToCropRect:[self convertRect:cropRect toView:self.zoomingView]];
_scrollView.zoomScale = _scrollView.zoomScale * newZoomScale;
} completion:^(BOOL finished) {
if (![self rotatedView:_imageView containsViewCompletely:_cropRectView])
{
// Damn, it's still broken - this happens a lot
}
else
{
// Woo! Fixed
}
_didDetectBadRotation = NO;
}];
Note I'm using AutoLayout which makes frames and bounds goofy.
Assume your image rectangle (blue in the diagram) and crop rectangle (red) have the same aspect ratio and center. When rotated, the image rectangle now has a bounding rectangle (green) which is what you want your crop scaled to (effectively, by scaling down the image).
To scale effectively, you need to know the dimensions of the new bounding rectangle and use a scale factor that fits the crop rect into it. The dimensions of the bounding rectangle are rather obviously
(a + b) x (c + d)
Notice that each segment a, b, c, d is either the adjacent or opposite side of a right triangle formed by the bounding rect and the rotated image rect.
a = image_rect_height * sin(rotation_angle)
b = image_rect_width * cos(rotation_angle)
c = image_rect_width * sin(rotation_angle)
d = image_rect_height * cos(rotation_angle)
Your scale factor is simply
MAX(crop_rect_width / (a + b), crop_rect_height / (c + d))
Here's a reference diagram:
Fill frame of overlay rect:
For a square crop you need to know new bounds of the rotated image which will fill the crop view.
Let's take a look at the reference diagram:
You need to find the altitude of a right triangle (the image number 2). Both altitudes are equal.
CGFloat sinAlpha = sin(alpha);
CGFloat cosAlpha = cos(alpha);
CGFloat hypotenuse = /* calculate */;
CGFloat altitude = hypotenuse * sinAlpha * cosAlpha;
Then you need to calculate the new width for the rotated image and the desired scale factor as follows:
CGFloat newWidth = previousWidth + altitude * 2;
CGFloat scale = newWidth / previousWidth;
I have implemented this method here.
I will answer using sample code, but basically this problem becomes really easy, if you will think in rotated view coordinate system.
UIView* container = [[UIView alloc] initWithFrame:CGRectMake(80, 200, 100, 100)];
container.backgroundColor = [UIColor blueColor];
UIView* content2 = [[UIView alloc] initWithFrame:CGRectMake(-50, -50, 150, 150)];
content2.backgroundColor = [[UIColor greenColor] colorWithAlphaComponent:0.5];
[container addSubview:content2];
[self.view setBackgroundColor:[UIColor blackColor]];
[self.view addSubview:container];
[container.layer setSublayerTransform:CATransform3DMakeRotation(M_PI / 8.0, 0, 0, 1)];
//And now the calculations
CGRect containerFrameInContentCoordinates = [content2 convertRect:container.bounds fromView:container];
CGRect unionBounds = CGRectUnion(content2.bounds, containerFrameInContentCoordinates);
CGFloat midX = CGRectGetMidX(content2.bounds);
CGFloat midY = CGRectGetMidY(content2.bounds);
CGFloat scaleX1 = (-1 * CGRectGetMinX(unionBounds) + midX) / midX;
CGFloat scaleX2 = (CGRectGetMaxX(unionBounds) - midX) / midX;
CGFloat scaleY1 = (-1 * CGRectGetMinY(unionBounds) + midY) / midY;
CGFloat scaleY2 = (CGRectGetMaxY(unionBounds) - midY) / midY;
CGFloat scaleX = MAX(scaleX1, scaleX2);
CGFloat scaleY = MAX(scaleY1, scaleY2);
CGFloat scale = MAX(scaleX, scaleY);
content2.transform = CGAffineTransformScale(content2.transform, scale, scale);
I'm using a UIPinchGestureRecognizer to adjust the width (not the height) of a view in a UIScrollView. It works with the pinch gesture's scale property, but the contentOffset of the scrollview doesn't change, so the view always increases on the right. This looks a bit better if I scale the contentOffset along with the width, since then the view increases from the left-most side of the screen.
The problem is that the location of the pinch is ignored - so it always appears that a pinch is on the left side of the screen.
I need to somehow factor in the location of the pinch to the contentOffset adjustment, so that the offset can be adjusted to keep the content at the pinch point to be in the same place.
Note: I cannot use built-in UIScrollView pinch-zoom gesture as I only want the zoom to be one dimension, horizontal. Also, I cannot use transforms on the UIView as I need to use the UIScrollView.
I was pinch zooming a graph, so the pinch adjusts the width constraint on the graph view.
Here is the pinch handler:
- (void) doPinch:(UIPinchGestureRecognizer*)pinch;
{
CGFloat width = self.graphWidthConstraint.constant;
CGFloat idealWidth = 1500;
CGFloat currentScale = width / idealWidth;
CGFloat scale = currentScale - (1.0 - pinch.scale);
CGFloat minScale = 0.5;
CGFloat maxScale = 3.0;
scale = MIN(scale, maxScale);
scale = MAX(scale, minScale);
CGPoint locationScrollview = [pinch locationInView:self.graphScrollView];
CGFloat pinchXNormalized = locationScrollview.x / width;
CGPoint locationView = [pinch locationInView:self.view];
// resize
CGFloat newWidth = idealWidth * scale;
self.graphWidthConstraint.constant = newWidth;
// set offset to position point under touch
CGFloat pinchXScaled = newWidth * pinchXNormalized;
CGFloat x = pinchXScaled - locationView.x;
self.graphScrollView.contentOffset = CGPointMake(x, 0);
pinch.scale = 1;
}
im using someone else's pinch gesture code for scaling which works perfect but its scaling my image in my photo editing app and once the user presses done scaling, i need the changes to be reflected and saved or another way to say it i need the image to actually be zoomed in and cropped if someone used pinch to scale. I figured i could use the amount they scaled * the frame size for uigraphicsbeginimagecontext but that strategy is not working since when the user scales the image and hits the done button the image gets saved smaller because this now very large size is getting squeezed into the view when what i really want it crop off any leftovers and not do any fitting.
- (IBAction)pinchGest:(UIPinchGestureRecognizer *)sender{
if (sender.state == UIGestureRecognizerStateEnded
|| sender.state == UIGestureRecognizerStateChanged) {
NSLog(#"sender.scale = %f", sender.scale);
CGFloat currentScale = self.activeImageView.frame.size.width / self.activeImageView.bounds.size.width;
CGFloat newScale = currentScale * sender.scale;
if (newScale < .5) {
newScale = .5;
}
if (newScale > 4) {
newScale = 4;
}
CGAffineTransform transform = CGAffineTransformMakeScale(newScale, newScale);
self.activeImageView.transform = transform;
scalersOfficialChange = newScale;
sender.scale = 1;
}
}
- (IBAction)doneMoverViewButtonPressed:(UIButton *)sender {
// turn off ability to move & scale
moverViewActive = NO;
NSLog(#"%f %f",dragOfficialChange.x,dragOfficialChange.y);
NSLog(#"%f",rotationOfficialChange);
NSLog(#"%f",scalersOfficialChange);
//problem area below...
CGSize newSize = CGSizeMake(self.activeImageView.bounds.size.width * scalersOfficialChange, self.activeImageView.bounds.size.height * scalersOfficialChange );
UIGraphicsBeginImageContext(newSize);
[self.activeImageView.image drawInRect:CGRectMake(dragOfficialChange.x, dragOfficialChange.y, self.layerContainerView.bounds.size.width, self.layerContainerView.bounds.size.height)];
self.activeImageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self hideMoveViewerAnimation];
//resets activeimageview coords
CGRect myFrame = self.layerContainerView.bounds;
myFrame.origin.x = 0;
myFrame.origin.y = 0;
self.activeImageView.frame = myFrame;
//reset changes values
dragOfficialChange.x = 0;
dragOfficialChange.y = 0;
rotationOfficialChange = 0;
scalersOfficialChange = 0;
}
first of all, can you make your question more clear? I suggest you want to draw your image in a rect and don't want to squeeze it, am I right?
Then lets try this method:
//The method: drawInRect:(CGRect) will scale your pic and squeeze it to fit the Rect area
//So if you dont want to scale your pic, you can use the method below
[image drawAsPatternInRect:(CGRect)_rect];
//This method would not scale your image and cut the needless part