Visual artifacts on UIView rotation with tiled background image - uiview

I have an iPad app with a standard UIViewController/UIView setup - all rotations are allowed. The UIView draws some tiled image as background (the tile is 256*256 pixels):
- (void)drawRect:(CGRect)rect
{
[[UIImage imageNamed: #"Background.png"] drawAsPatternInRect: rect];
}
When I turn my iPad I can see that during the rotation the image pattern of the original orientation is scaled to fit the new orientation. Then - immediately after the animation is finished - the view redraws its background pattern with the final configuration which is unscaled. The switching from a scaled to an unscaled pattern looks a bit ugly.
Is there a way to circumvent (or hide) this strecthing of the background pattern?

Why not use a pattern image as background "color"? This automatically results in a tiled pattern and avoids any stunts with drawRect(). For example:
UIImage *backgroundTile = [UIImage imageNamed: #"Background.png"];
UIColor *backgroundPattern = [[UIColor alloc] initWithPatternImage:backgroundTile];
[myView setBackgroundColor:backgroundPattern];
[backgroundPattern release];

to put simply,
[myView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed: #"Background.png"] ] ];

Related

iOS image blending like Fused app

I want to blend two UIImages as Fused App is doing:
https://itunes.apple.com/us/app/fused-double-exposure-video/id869117407?mt=8
What Fused is doing, it takes two images (foreground & background) and apply blending in such a way that background remains the same and user can move,rotate & size the foreground image. I attached two images for better understanding. I want to achieve the same behaviour in my app. I have tried all CoreImage & CoreGraphics but I could not achieve this. Help needed from all of you.
First Screen: After applying Overly blend mode.
Second Screen: Change the size of foreground image:
My Result:
You can achieve what you want by using CHTStickerView, I've used it before and it works great. CHTStickerView is a movable, resizable, rotatable UIView with one finger, which is fully customizable.
Use CHTStickerView as your foreground image and UIImageView as your background image.
So your code should look something like this:
- (void)viewDidLoad {
[super viewDidLoad];
//background
UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:self.view.frame];
[backgroundImageView setImage:#"background.png"];
[self.view addSubview:backgroundImageView];
//foreground
UIImageView *foregroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
[foregroundImageView setImage:[UIImage imageNamed:#"foreground.png"]];
CHTStickerView *stickerView = [[CHTStickerView alloc] initWithContentView:foregroundImageView]; //set your foreground image as content in CHTStickerView
stickerView.center = self.view.center;
stickerView.delegate = self;
[stickerView setImage:[UIImage imageNamed:#"Close"] forHandler:CHTStickerViewHandlerClose];
[stickerView setImage:[UIImage imageNamed:#"Rotate"] forHandler:CHTStickerViewHandlerRotate];
[self.view addSubview:stickerView];
}
UPDATE
Alright I downloaded the app and checked out blend. I think what the app is doing is just getting the opacity value of the foreground image with the slide bar and drawing the foreground image (opacity set) on the background image.
So to set the opacity of a UIImage check this out: How to set the opacity/alpha of a UIImage?
And to draw and image over another check this out: Draw another image on a UIImage
To summarize, what you need to do is:
1) get the position and size of the CHTStickerView after user rotated and resize
2) get the UIImage from CHTStickerView, get the opacity value from slider
3) set opacity to image and draw image on your background image
Hope this helps!

UIVibrancyEffect On iOS 7

So I've been playing around with the iOS 8 beta and implementing the new UIEffectViews in the places that my app needed them. Now I've run into the issue that I still want to have backwards compatibility for iOS 7, but maintain the vibrancy effect because it really helps readability. I've used UIToolbars in the past for a blur effect, and they work great, but not for vibrancy. I thought I'd subclass UIView and add a toolbar subview and then do some clever rendering to sort of achieve the vibrancy effect which would look like this:
1. render the toolbar to a UIImage
2. render the vibrant content to a UIImage
3. mask the toolbar image to the vibrant content image mask
4. mess with the saturation and brightness
5. have a subview of the UIView display the final result over the toolbar
I've tried doing this in drawRect: of the UIView but it doesn't want to redraw every frame, and setting a timer really messes with animation, even though the render time isn't very high. If anyone can point me to sample code or a open source library, it would be much appreciated.
Thanks.
So I never posted an answer, but I did figure it out.
The brute force approach I tried was to use Core Image effects. I would render the superview to a UIImage, blur it, then overlay it on a toolbar with the dark style. This looked great, but even on a GPU context on my 5S, it was pretty slow, so theres no way it would work on other devices. This is the best I could get it to look, and would work great for static content, but is not practical for real-time.
I was able to achieve a real time version, but it doesn't look quite as good. Basically what I do is render all the vibrant content to a image and use it for a mask for a view. Then I make the view barely visible (like .2 alpha), and then put it over a toolbar. It doesn't look quite as vibrant as iOS8, or the original CI version, but it works great and preforms well.
Heres a bit of code you can just copy and paste if you really want:
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.backgroundColor = [UIColor colorWithWhite:1 alpha:0.2];
maskingContents = [[UIView alloc] initWithFrame:self.bounds];
[self addSubview:maskingContents];
}
return self;
}
-(void)addSubview:(UIView *)view
{
if (![view isEqual:maskingContents])
{
[maskingContents setHidden:NO];
[maskingContents addSubview:view];
//now we need to mask it
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
[maskingContents.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* mask = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//apply the mask
CALayer* maskLayer = [CALayer layer];
maskLayer.frame = self.bounds;
[maskLayer setContents:(id)mask.CGImage];
[self.layer setMask:maskLayer];
[maskingContents setHidden:YES];
} else [super addSubview:view];
}
-(void)forceVibrancyUpdate
{
[maskingContents setHidden:NO];
//now we need to mask it
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
[maskingContents.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* mask = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//apply the mask
CALayer* maskLayer = [CALayer layer];
maskLayer.frame = self.bounds;
[maskLayer setContents:(id)mask.CGImage];
[self.layer setMask:maskLayer];
[maskingContents setHidden:YES];
}
#end
If you want to dynamically update the content inside the vibrancy view, you would call forceVibrancyUpdate, as that would re-render the mask and apply it. Hope this helped everyone.

Blur screen with iOS 7's snapshot API

I believe the NDA is down, so I can ask this question. I have a UIView subclass:
BlurView *blurredView = ((BlurView *)[self.view snapshotViewAfterScreenUpdates:NO]);
blurredView.frame = self.view.frame;
[self.view addSubview:blurredView];
It does its job so far in capturing the screen, but now I want to blur that view. How exactly do I go about this? From what I've read I need to capture the current contents of the view (context?!) and convert it to CIImage (no?) and then apply a CIGaussianBlur to it and draw it back on the view.
How exactly do I do that?
P.S. The view is not animated, so it should be OK performance wise.
EDIT: Here is what I have so far. The problem is that I can't capture the snapshot to a UIImage, I get a black screen. But if I add the view as a subview directly, I can see the snapshot is there.
// Snapshot
UIView *view = [self.view snapshotViewAfterScreenUpdates:NO];
// Convert to UIImage
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Apply the UIImage to a UIImageView
BlurView *blurredView = [[BlurView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)];
[self.view addSubview:blurredView];
blurredView.imageView.image = img;
// Black screen -.-
BlurView.m:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.imageView = [[UIImageView alloc] init];
self.imageView.frame = CGRectMake(20, 20, 200, 200);
[self addSubview:self.imageView];
}
return self;
}
Half of this question didn't get answered, so I thought it worth adding.
The problem with UIScreen's
- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates
and UIView's
- (UIView *)resizableSnapshotViewFromRect:(CGRect)rect
afterScreenUpdates:(BOOL)afterUpdates
withCapInsets:(UIEdgeInsets)capInsets
Is that you can't derive a UIImage from them - the 'black screen' problem.
In iOS7 Apple provides a third piece of API for extracting UIImages, a method on UIView
- (BOOL)drawViewHierarchyInRect:(CGRect)rect
afterScreenUpdates:(BOOL)afterUpdates
It is not as fast as snapshotView, but not bad compared to renderInContext (in the example provided by Apple it is five times faster than renderInContext and three times slower than snapshotView)
Example use:
UIGraphicsBeginImageContextWithOptions(image.size, NULL, 0);
[view drawViewHierarchyInRect:rect];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Then to get a blurred version
UIImage* lightImage = [newImage applyLightEffect];
where applyLightEffect is one of those Blur category methods on Apple's UIImage+ImageEffects category mentioned in the accepted answer (the enticing link to this code sample in the accepted answer doesn't work, but this one will get you to the right page: the file you want is iOS_UIImageEffects).
The main reference is to WWDC2013 session 226, Implementing Engaging UI on iOS
By the way, there is an intriguing note in Apple's reference docs for renderInContext that hints at the black screen problem..
Important: The OS X v10.5 implementation of this method does not support the entire Core Animation composition model. QCCompositionLayer, CAOpenGLLayer, and QTMovieLayer layers are not rendered. Additionally, layers that use 3D transforms are not rendered, nor are layers that specify backgroundFilters, filters, compositingFilter, or a mask values. Future versions of OS X may add support for rendering these layers and properties.
The note hasn't been updated since 10.5, so I guess 'future versions' may still be a while off, and we can add our new CASnapshotLayer (or whatever) to the list.
Sample Code from WWDC ios_uiimageeffects
There is a UIImage category named UIImage+ImageEffects
Here is its API:
- (UIImage *)applyLightEffect;
- (UIImage *)applyExtraLightEffect;
- (UIImage *)applyDarkEffect;
- (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor;
- (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius
tintColor:(UIColor *)tintColor
saturationDeltaFactor:(CGFloat)saturationDeltaFactor
maskImage:(UIImage *)maskImage;
For legal reason I can't show the implementation here, there is a demo project in it. should be pretty easy to get start with.
To summarize how to do this with foundry's sample code, use the following:
I wanted to blur the entire screen just slightly so for my purposes so I'll use the main screen bounds.
CGRect screenCaptureRect = [UIScreen mainScreen].bounds;
UIView *viewWhereYouWantToScreenCapture = [[UIApplication sharedApplication] keyWindow];
//screen capture code
UIGraphicsBeginImageContextWithOptions(screenCaptureRect.size, NO, [UIScreen mainScreen].scale);
[viewWhereYouWantToScreenCapture drawViewHierarchyInRect:screenCaptureRect afterScreenUpdates:NO];
UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//blur code
UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0];
UIImage *blurredImage = [capturedImage applyBlurWithRadius:1.5 tintColor:tintColor saturationDeltaFactor:1.2 maskImage:nil];
//or use [capturedImage applyLightAffect] but I thought that was too much for me
//use blurredImage in whatever way you so desire!
Notes on the screen capture part
UIGraphicsBeginImageContextWithOptions() 2nd argument is opacity. It should be NO unless you have nothing with any alpha other than 1. If you return yes the screen capture will not look at transparency values so it will go faster but will probably be wrong.
UIGraphicsBeginImageContextWithOptions() 3rd argument is the scale. Probably want to put in the scale of the device like I did to make sure and differentiate between retina and non-retina. But I haven't really tested this and I think 0.0f also works.
drawViewHierarchyInRect:afterScreenUpdates: watch out what you return for the screen updates BOOL. I tried to do this right before backgrounding and if I didn't put NO the app would go crazy with glitches when I returned to the foreground. You might be able to get away with YES though if you're not leaving the app.
Notes on blurring
I have a very light blur here. Changing the blurRadius will make it blurrier, and you can change the tint color and alpha to make all sorts of other effects.
Also you need to add a category for the blur methods to work...
How to add the UIImage+ImageEffects category
You need to download the category UIImage+ImageEffects for the blur to work. Download it here after logging in: https://developer.apple.com/downloads/index.action?name=WWDC%202013
Search for "UIImageEffects" and you'll find it. Just pull out the 2 necessary files and add them to your project. UIImage+ImageEffects.h and UIImage+ImageEffects.m.
Also, I had to Enable Modules in my build settings because I had a project that wasn't created with xCode 5. To do this go to your target build settings and search for "modules" and make sure that "Enable Modules" and "Link Frameworks Automatically" are both set to yes or you'll have compiler errors with the new category.
Good luck blurring!
Check WWDC 2013 sample application "running with a snap".
The blurring is there implemented as a category.

UITableView Background Scroll but NOT Repeat

I am trying to set a UITableView background using the following method:
[self.tableView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"backgroundImage.png"]]];
This works great for making the background scroll with the table. However, my background image fades into a solid color, so instead of the background repeating, I'd love for it to just scroll up and just fit to the screen height. Then I can set self.view's backgroundColor to be the solid color and it will look great.
Other options seem to be blitting a small image at the bottom, but this seems complicated and I didn't quite understand how to draw the background and blit using CGContext.
Can someone tell me how to do this?
I'm not sure whether this will work but you should try creating a resizeable UIImage for the background:
If you want the last line of pixels to repeat you would call the
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode
on your image ( [UIImage imageNamed:#"backgroundImage.png"] )
with edgeinsets: UIEdgeInsetsMake(backgroundImage.size.height-1,0,0,0)
and resizingMode: UIImageResizingModeStretch
the complete call would look like
UIImage* backgroundImage = [UIImage imageNamed:#"backgroundImage.png"];
UIImage* newBackgroundImage = [backgroundImage resizableImageWithCapInsets:UIEdgeInsetsMake(backgroundImage.size.height-1,0,0,0) resizingMode:UIImageResizingModeStretch];
And now you could try to use this image for the pattern creation:
[self.tableView setBackgroundColor:[UIColor colorWithPatternImage:newBackgroundImage]];
This worked for me:
UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:self.tableView.frame];
bgImageView.image = [UIImage imageNamed:#"bg"];
bgImageView.contentMode = UIViewContentModeTop;
[self.tableView addSubview:bgImageView];
[self.tableView sendSubviewToBack:bgImageView];
In my case it worked fine. I didn't test it with a lot of cells which are reused. But it should work :D

Center [UIColor colorWithPatternImage]?

I couldn't find anything on how you can center the 'image' when you use (maybe you can't):
[self setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"background"]]];
Setting my [self setContentMode:UIContentModeCenter]; doesnt help.
Do I have to manually draw the image (either in drawRect or set the content of the CALayer? Which one if preferable?
I think you're on the wrong path here: you create a UIColor from a pattern (pattern already implies this is a repeating image). All in all- you can't have your pattern not repeat and centered.
If you just want simple image as background of your UIView, just add it as a subview and center it.
UIImage* img = [UIImage imageNamed:#"yourfile.png"];
UIImageView* imgView = [[UIImageView alloc]initWithImage: img];
[yourUIView addSubview: imgView];
imgView.center = CGPointMake(yourUIView.frame.size.width/2, yourUIView.frame.size.height/2);
Now - add more subviews to your "yourUIView" view and they'll show on top of the image - thus the image becoming the background.
So... no need to draw anything yourself.

Resources