CATiledLayer to CALayer - iphone

I have a view with a CATiledLayer backing. I want to take the visible tiles from this CATiledLayer UIView and add it to another view as its CALayer backing, thus recreating the visible image in another UIView that doesnt use CATiledLayer.
The reason I want to do this is I will use this second UIView to mask the effect of updating the CATiledLayer backed UIView - this currently produces a flicker as all tiles are re-loaded.
The problem is, I'm not totally sure how i would do this. Any ideas?

CATiledLayer is a subclass of CALayer providing a way to
asynchronously provide tiles of the layer's content, potentially
cached at multiple levels of detail.
You can render the visible things in the layer into a CGContextRef with:
- (void)renderInContext:(CGContextRef)ctx
And then use this to update your other layer by settings its delegate and implementing the
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
ss shown here http://www.raywenderlich.com/2502/introduction-to-calayers-tutorial
But honestly I don't think this is efficient.

Your real problem here is the flickering. I had a similar problem on a view with a custom CALayer backing it, this was part of the solution:
Create a custom subclass of your CALayer and implement the following method:
- (void) display {
self.contents = nil;
[super display];
}
This fixed a set of problems for me, but may not fix it for you. The alternative for you may be to disable transactions while you update:
From CATransaction Class Reference
setDisableActions: Sets whether actions triggered as a result of
property changes made within this transaction group are suppressed.
So to use this:
[CATransaction begin];
[CATransaction setDisableActions:YES];
// do updating/flickering stuff
[self doFlickeringThing];
[CATransaction commit];

Related

Remove or change color of frame around UIWebView document display?

I'm using a UIWebView to display a variety of file types (so I can't use a specialized PDF viewer) embedded into my main view (so I can't use a modal document interaction controller). My main view has a background design that clashes with the light gray frame that appears around documents in the UIWebView. Does anyone know a way to remove that gray frame, make it transparent or change its color?
I'm familiar with and have used the techniques for changing the background color of the UIWebView to avoid a "color flash" while it loads, and for removing the top and bottom shadow that appear when "overscrolling" the web view, but I haven't seen anyone address this gray frame. (It only appears when displaying documents like .doc or .pdf, not when displaying HTML content.) I've hidden all the images that are subviews of the UIWebView's scroll view, so apparently this is coming from somewhere else.
This question was written while iOS 4 was current, but in iOS 5 and later, simply setting the backgroundColor and opaque properties of the UIWebView will remove that gray frame:
myWebView.opaque = NO;
myWebView.backgroundColor = [UIColor clearColor];
You can change WebView's background color by assigning its backgroundColor property:
myWebView.backgroundColor = [UIColor redColor]; // will make red bakground
If you want transparency use [UIColor clearColor] instead. But remember - by making your views tranparent you can worsen app's performance.
Since this has been around for a while I'll just throw some ideas out there.
You may be able to utilize the stringByEvaluatingJavaScriptFromString: method of the UIWebView class to manipulate the document object model if the UIWebView treats the loaded document as a page, but this method has some limitations.
Other than that, the only thing you really have left at your disposal is manipulating the view hierarchy to modify any subviews of the UIWebView, but there may not be anything for you manipulate if the UIWebView class renders the viewer directly rather than creating a hierarchy.
It looks like it is not possible to remove the border from a UIWebView but could you not use CGContextDrawPDFPage() as Apple show here: http://developer.apple.com/library/ios/#samplecode/ZoomingPDFViewer/Introduction/Intro.html
Try this,
self.webview.backgroundColor = [UIColor whiteColor];
for (UIView* subView in [self.webview subviews])
{
if ([subView isKindOfClass:[UIScrollView class]]) {
for (UIView* shadowView in [subView subviews])
{
if ([shadowView isKindOfClass:[UIImageView class]]) {
[shadowView setHidden:YES];
}
}
}
}
This may help you. :-)
You need a bunch of CoreAnimation magic:
- (void) hideShadowInLayer:(CALayer *) layer
{
for (CALayer *l in layer.sublayers) {
l.shadowOpacity = 0;
[self hideShadowInLayer:l];
}
}
- (void) hideShadows
{
[CATransaction begin];
[CATransaction setValue:(id) kCFBooleanTrue forKey:kCATransactionDisableActions];
[self hideShadowInLayer:webView.layer];
[CATransaction commit];
}
You need to perform hideShadows method somewhere AFTER loading your document and while you are scrolling it (I guess scrollViewDidScroll of webView.scrollView.delegate is a good place). You also need to include QuartzCore framework to your project.
What's going on here:
Any view uses something called layer for rendering. Layers can have its own hierarchy and every layer can have its own border and shadow, so the frame that annoying you is the shadow of one of them. Bad thing - UIWebView recreates it while scrolling - so you need to use this method constantly. And I guess shadowOpacity has a default animation attached to it, so you need CATransaction to disable it.

How to add a gradient to a scrollview?

I am trying to add a bunch of gradients to different UIScrollView's and UITableView's. The most common example of how to achieve this that i have come across is from Matt Galagher's awesome blog where he posted an example of how to use gradients here:
http://cocoawithlove.com/2009/08/adding-shadow-effects-to-uitableview.html
My question though is what advantages/benefits do you gain by inserting the gradient in the layoutSubviews method vs setting up the gradient in the viewDidLoad method? I realize that by goin the viewDidLoad route you would have to update the view manually when the orientation changes but it would seem from a performance standpoint that this method would only be called once when the view loads and then again when the orientation changes. In contrast the layoutSubviews method gets called everytime time the view changes which in the case of a scrollview/tableview is a lot!
//
// Construct the origin shadow if needed
//
if (!originShadow)
{
originShadow = [self shadowAsInverse:NO];
[self.layer insertSublayer:originShadow atIndex:0];
}
else if (![[self.layer.sublayers objectAtIndex:0] isEqual:originShadow])
{
[self.layer insertSublayer:originShadow atIndex:0];
}
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
//
// Stretch and place the origin shadow
//
CGRect originShadowFrame = originShadow.frame;
originShadowFrame.size.width = self.frame.size.width;
originShadowFrame.origin.y = self.contentOffset.y;
originShadow.frame = originShadowFrame;
[CATransaction commit];
He also seems to be resizing the frame everytime the method is called? Wouldnt it be better to initialize and size the gradient in the viewDidLoad method and then do any resizing when/if the orientation changes?
Pretty sure im missing something here so any clarification would be appreciated.
Thx
I wouldn't create the gradient in layoutSubviews. Layout subviews might get called more often than is optimal for this kind of drawing. By doing something CPU intensive in layoutSubviews, like creating a gradient, you might adversely impact performance.
Instead, what I would do is put your gradient on a subview and then add your subview into your scrollview (viewDidLoad, init, or awakeFromNib is good for this) and let it handle it's drawing automatically. Then, in layoutSubviews, adjust the layout of your subview, and let it handle figuring out what portions of the view need to be redrawn to update things.

Vector like drawing for zoomable UIScrollView

I have a zoomable UIScrollView with some CATextLayers and simple CALayers in it.
They get rendered fine but the problem is when they are zoomed they become blurry. (Even if I redraw them)
What would be my options to get my text not blurry when the view is zoomed?
Should I use another thing? enable something in CATextLayer/CALayer? Any idea is welcomed ;)
I am using CALayers because, as suggested in documentation, CALayers are lighter than UIViews and I have hundreds of them. Currently it works smoothly. I have tried with UIWebView and my CALayer version is faster ;)
Thanks in advance.
iOS rasterizes the text before the scale-up occurs, that's why it's so blurry. You only need to fix one property of your CATextLayer, contentsScale, to get a higher quality render after zooming. Implement this UIScrollViewDelegate method:
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView
withView:(UIView *)view
atScale:(float)scale
{
[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithBool:YES]
forKey:kCATransactionDisableActions];
uglyBlurryTextLayer.contentsScale = scale;
[CATransaction commit];
}
This tells the layer to use more pixels to render the text, and it disables Core Animation when making that particular change.

iPhone Dev: Animating PNG Sequences

What is the best or recommended technique for animating PNG Sequences.
Heres what I've learned:
Do it Manually
Using MutableArrays containing Strings, you can animate a UIImageView with a timer which increments an index number
UIImage - animation methods
This works, the only problem is to find if an image has completed its animation, you have to check the isAnimating BOOL, and to do that you need a timer.
What is the best and recommended?
Looking to do Oldschool game sprite animations,
ie:
Idle Animation
Attack Animation
Walk Animation
ect...
Let me know if any one has something.
#lessfame
Example to animate arrows
UIImage* img1 = [UIImage imageNamed:#"fleche1.png"];
UIImage* img2 = [UIImage imageNamed:#"fleche2.png"];
NSArray *images = [NSArray arrayWithObjects:img1,img2, nil];
UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 160.0, 160.0)];
[imageView setAnimationImages:images];
[imageView setAnimationRepeatCount:100];
[imageView setAnimationDuration:3.0];
imageView.center = myView.center;
[imageView startAnimating];
[myView addSubview:imageView];
[imageView release];
Easiest way is to use Core Animation layers to do sprite animation:
Make a 'multi-cell' image strip (could be PNG or JPG) of all the various moves for the sprite. Make each 'cell' be a fixed height or width.
Put the image in a UIImageView.
Take the CALayer of the view, and adjust the contentsRect property of the layer. This acts as a clipping rectangle for the sprite. To animate sprite all you have to do is move the contentsRect over to the next cell position in the image strip.
Something like this will do it (assuming you've already calculated the newSpritePosition.
[CATransaction begin];
[CATransaction setDisableActions:YES];
spriteLayer.contentsRect = newSpritePosition;
[CATransaction commit];
(If you don't do the second line, then you'll get a default slide animation instead of a 'jump' to the next state.)
With this technique you can rotate through all the frames of the sprite -- much like a flipbook. CALAyer transactions are optimized so you should get pretty fast frame rates. You can set an animationDidStop completion handler to move to the next state of the sprite or loop back to the beginning frame.
It depends on how you are going to use the sprites. If you just need a simple looping sprite then the UIImage method is great. If you want more granular control then you will be happier loading the images into an array and cycling them using a NSTimer to handle the timing. Personally I use the array method most often because it leaves me more options in the future (like detecting when animations have completed). One more suggestion would be to check out the cocos2d project. Its sprite is alot more powerful than either of these suggestions.
As I said in another answer, I found this to be a good way: PNG Animation method by Moses DeJong
From his words:
This example implements an animation oriented view controller that simply waits to read the PNG image data for a frame until it is needed. Instead of alllocating many megabytes, this class run in about a half a meg of memory with about a 5-10% CPU utilization on a 2nd gen iPhone.
I'm still unsure exactly how it's done. I believe it basically uses UIImageView to cache up AVAudioPlayer.

How do I reset after a UIScrollView zoom?

I have a Graph being drawn inside a UIScrollView. It's one large UIView using a custom subclass of CATiledLayer as its layer.
When I zoom in and out of the UIScrollView, I want the graph to resize dynamically like it does when I return the graph from viewForZoomingInScrollView. However, the Graph redraws itself at the new zoom level, and I want to reset the transform scale to 1x1 so that the next time the user zooms, the transform starts from the current view. If I reset the transform to Identity in scrollViewDidEndZooming, it works in the simulator, but throws an EXC_BAD_ACCSES on the device.
This doesn't even solve the issue entirely on the simulator either, because the next time the user zooms, the transform resets itself to whatever zoom level it was at, and so it looks like, if I was zoomed to 2x, for example, it's suddenly at 4x. When I finish the zoom, it ends up at the correct scale, but the actual act of zooming looks bad.
So first: how do I allow the graph to redraw itself at the standard scale of 1x1 after zooming, and how do I have a smooth zoom throughout?
Edit: New findings
The error seems to be "[CALayer retainCount]: message sent to deallocated instance"
I'm never deallocating any layers myself. Before, I wasn't even deleting any views or anything. This error was being thrown on zoom and also on rotate. If I delete the object before rotation and re-add it afterward, it doesn't throw the exception. This is not an option for zooming.
I can't help you with the crashing, other than tell you to check and make sure you aren't unintentionally autoreleasing a view or layer somewhere within your code. I've seen the simulator handle the timing of autoreleases differently than on the device (most often when threads are involved).
The view scaling is an issue with UIScrollView I've run into, though. During a pinch-zooming event, UIScrollView will take the view you specified in the viewForZoomingInScrollView: delegate method and apply a transform to it. This transform provides a smooth scaling of the view without having to redraw it each frame. At the end of the zoom operation, your delegate method scrollViewDidEndZooming:withView:atScale: will be called and give you a chance to do a more high-quality rendering of your view at the new scale factor. Generally, it's suggested that you reset the transform on your view to be CGAffineTransformIdentity and then have your view manually redraw itself at the new size scale.
However, this causes a problem because UIScrollView doesn't appear to monitor the content view transform, so on the next zoom operation it sets the transform of the content view to whatever the overall scale factor is. Since you've manually redrawn your view at the last scale factor, it compounds the scaling, which is what you're seeing.
As a workaround, I use a UIView subclass for my content view with the following methods defined:
- (void)setTransformWithoutScaling:(CGAffineTransform)newTransform;
{
[super setTransform:newTransform];
}
- (void)setTransform:(CGAffineTransform)newValue;
{
[super setTransform:CGAffineTransformScale(newValue, 1.0f / previousScale, 1.0f / previousScale)];
}
where previousScale is a float instance variable of the view. I then implement the zooming delegate method as follows:
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale;
{
[contentView setTransformWithoutScaling:CGAffineTransformIdentity];
// Code to manually redraw view at new scale here
contentView.previousScale = scale;
scrollView.contentSize = contentView.frame.size;
}
By doing this, the transforms sent to the content view are adjusted based on the scale at which the view was last redrawn. When the pinch-zooming is done, the transform is reset to a scale of 1.0 by bypassing the adjustment in the normal setTransform: method. This seems to provide the correct scaling behavior while letting you draw a crisp view at the completion of a zoom.
UPDATE (7/23/2010): iPhone OS 3.2 and above have changed the behavior of scroll views in regards to zooming. Now, a UIScrollView will respect the identity transform you apply to a content view and only provide the relative scale factor in -scrollViewDidEndZooming:withView:atScale:. Therefore, the above code for a UIView subclass is only necessary for devices running iPhone OS versions older than 3.2.
Thanks to all the previous answers, and here is my solution.
Implement UIScrollViewDelegate methods:
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return tmv;
}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
CGPoint contentOffset = [tmvScrollView contentOffset];
CGSize contentSize = [tmvScrollView contentSize];
CGSize containerSize = [tmv frame].size;
tmvScrollView.maximumZoomScale = tmvScrollView.maximumZoomScale / scale;
tmvScrollView.minimumZoomScale = tmvScrollView.minimumZoomScale / scale;
previousScale *= scale;
[tmvScrollView setZoomScale:1.0f];
[tmvScrollView setContentOffset:contentOffset];
[tmvScrollView setContentSize:contentSize];
[tmv setFrame:CGRectMake(0, 0, containerSize.width, containerSize.height)];
[tmv reloadData];
}
tmv is my subclass of UIView
tmvScrollView — outlet to UIScrollView
set maximumZoomScale and minimumZoomScale before
create previousScale instance variable and set its value to 1.0f
Works for me perfectly.
BR, Eugene.
I was just looking to reset on load to default zoom scale, because when I zoom it, scrollview is having same zoom scale for next time until it gets deallocated.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.scrollView.setZoomScale(1.0, animated: false)
}
OR
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated]
[self.scrollView setZoomScale:1.0f];
}
Changed the game.
I have a detailed discussion of how (and why) UIScrollView zooming works at github.com/andreyvit/ScrollingMadness/.
(The link also contains a description of how to programmatically zoom UIScrollView, how to emulate Photo Library-style paging+zooming+scrolling, an example project and ZoomScrollView class that encapsulates some of the zooming magic.)
Quote:
UIScrollView does not have a notion of a “current zoom level”, because each subview it contains may have its own current zoom level. Note that there is no field in UIScrollView to keep the current zoom level. However we know that someone stores that zoom level, because if you pinch-zoom a subview, then reset its transform to CGAffineTransformIdentity, and then pinch again, you will notice that the previous zoom level of the subview has been restored.
Indeed, if you look at the disassembly, it is UIView that stores its own zoom level (inside UIGestureInfo object pointed to by the _gestureInfo field). It also has a set of nice undocumented methods like zoomScale and setZoomScale:animated:. (Mind you, it also has a bunch of rotation-related methods, maybe we're getting rotation gesture support some day soon.)
However, if we create a new UIView just for zooming and add our real zoomable view as its child, we will always start with zoom level 1.0. My implementation of programmatic zooming is based on this trick.
A fairly reliable approach, appropriate to iOS 3.2 and 4.0 and later, is as follows. You must be prepared to supply your scalable view (the chief subview of the scroll view) in any requested scale. Then in scrollViewDidEndZooming: you will remove the blurred scale-transformed version of this view and replace it with a new view drawn to the new scale.
You will need:
An ivar for maintaining the previous scale; let's call it oldScale
A way of identifying the scalable view, both for viewForZoomingInScrollView: and for scrollViewDidEndZooming:; here, I'm going to apply a tag (999)
A method that creates the scalable view, tags it, and inserts it into the scroll view (here's I'll call it addNewScalableViewAtScale:). Remember, it must do everything according to scale - it sizes the view and its subviews or drawing, and sizes the scroll view's contentSize to match.
Constants for the minimumZoomScale and maximumZoomScale. These are needed because when we replace the scaled view by the detailed larger version, the system is going to think that the current scale is 1, so we must fool it into allowing the user to scale the view back down.
Very well then. When you create the scroll view, you insert the scalable view at scale 1.0. This might be in your viewDidLoad, for example (sv is the scroll view):
[self addNewScalableViewAtScale: 1.0];
sv.minimumZoomScale = MIN;
sv.maximumZoomScale = MAX;
self->oldScale = 1.0;
sv.delegate = self;
Then in your scrollViewDidEndZooming: you do the same thing, but compensating for the change in scale:
UIView* v = [sv viewWithTag:999];
[v removeFromSuperview];
CGFloat newscale = scale * self->oldScale;
self->oldScale = newscale;
[self addNewScalableViewAtScale:newscale];
sv.minimumZoomScale = MIN / newscale;
sv.maximumZoomScale = MAX / newscale;
Swift 4.* and Xcode 9.3
Setting scrollView zoom scale to 0 will reset your scrollView to it's initial state.
self.scrollView.setZoomScale(0.0, animated: true)
Note that the solution provided by Brad has one problem though: if you keep programmatically zooming in (let's say on double tap event) and let user manually (pinch-out) zoom out, after some time the difference between the true scale and the scale UIScrollView is tracking will grow too big, so the previousScale will at some point fall out of float's precision which will eventually result in an unpredictable behaviour