How to do vignette effect on iOS? - iphone

When UIAlertViews pop up, there is a vignette effect in the background. That is, the edges are darker and the center is lighter.
I was wondering if this vignette effect was built into Cocoa Touch. I would like to show the vignette behind one of my custom views.

It is built into UIKit (as UIAlertView is part of UIKit), but it's not public.
It shouldn't be too hard to create the same effect, though. It's just a radial gradient, which you can draw in code or Photoshop.
UPDATE: If you must know, the background is a class called _UIAlertNormalizingOverlayWindow with the following class hierarchy:
_UIAlertNormalizingOverlayWindow
_UIAlertOverlayWindow
UIWindow

Create a class called VignetteEffect as a subclass of UIView
Add this code to your -drawRect: method:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorSpaceRef colSp = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColors(colSp, (__bridge CFArrayRef)[NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0 green:0 blue:0 alpha:0] CGColor], (id)[[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5] CGColor], nil], 0);
CGContextDrawRadialGradient(context, gradient, self.center, 0, self.center, self.frame.size.height+self.frame.size.height/4, 0);
CGColorSpaceRelease(colSp);
CGGradientRelease(gradient);
}
Tweak the values to your liking.
Add it to any view you have. Et voila. A nice vignette effect.

In fact this effect is achieved by an extra image - a separate window with an imageview is shown underneath a uialertview. That window makes it so you can't select or touch any other views. If you want that image it can be found right here

SVProgressHud does this type of effect, look at the code where SVProgressHUDMaskTypeGradient is detailed.

I contest the picked answer is not correct and is potentially dangerous. Here's my solution:
I copied the gradient drawing code from SVProgressHud into my fork of SSGradientView:
SSGradientView *vignette = [SSGradientView new];
vignette.frame = [UIScreen mainScreen].currentBounds;
vignette.backgroundColor = [UIColor clearColor];
vignette.direction = SSGradientViewDirectionRadial;
UIColor *startColor = // We just need the colorspace.
UIColor *endColor = // Visible vignette color.
vignette.colors = #[
[startColor colorWithAlphaComponent:0.0f],
[endColor colorWithAlphaComponent:1.0f] ];
vignette.locations = #[ #0.4f, #1.0f ];
[view insertSubview:vignette atIndex:0]; // Or equivalent.

Related

iphone - Focus effect (just like UIAlertView)

I know title of my question is so bad, but I don't know how to describe it.
When an UIAlertView pops up, anything else on the screen (except the UIAlertView) becomes a bit darker but can be seen. I call this as Focus effect, because you will know clearly and directly that now the UIAlertView is the focus.
So how can I implement such a focus effect?
thanks
Just add a translucent view below the view you want to "focus" on.
Simple example:
UIView *shieldView = [[[UIView alloc] initWithFrame:myView.bounds] autorelease];
shieldView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.7];
[myView.superview insertSubview:shieldView belowSubview:myView];
UIAlertView actually uses an image with a radial gradient instead of a simple color, in order to highlight the center of the view.
I know this post is a bit old but I thought it might help someone.
Use this code to generate the radial gradient background:
- (UIImage *)radialGradientImage:(CGSize)size start:(float)start end:(float)end centre:(CGPoint)centre radius:(float)radius{
UIGraphicsBeginImageContextWithOptions(size, YES, 1);
size_t count = 2;
CGFloat locations[2] = {0.0, 1.0};
CGFloat components[8] = {start, start, start, 1.0, end, end, end, 1.0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef grad = CGGradientCreateWithColorComponents (colorSpace, components, locations, count);
CGColorSpaceRelease(colorSpace);
CGContextDrawRadialGradient (UIGraphicsGetCurrentContext(), grad, centre, 0, centre, radius, kCGGradientDrawsAfterEndLocation);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGGradientRelease(grad);
UIGraphicsEndImageContext();
return image;}
Define gradient in the .h file like so:
UIImageView *gradient;
Call your gradient like so:
- (void)addGradient{
CGSize size = self.view.bounds.size;
CGPoint centre = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2);
float startColor = 1.0f;
float endColor = 0.0f;
float radius = MIN(self.view.bounds.size.width/4, self.view.bounds.size.height/4);
gradient = [[UIImageView alloc] initWithImage:[self radialGradientImage:size
start:startColor
end:endColor
centre:centre
radius:radius]];
[gradient setBackgroundColor:[UIColor clearColor]];
[gradient setUserInteractionEnabled:YES];
[gradient setAlpha:0.6f];
[self.view addSubview:gradient];}
UIAlertView works like this. It fades in an alpha mask image to dim out the background. Once that animation is finished it starts the "bounce in" animation of the dialog.
So to reproduce it you need first to generate an alpha mask with a "bright spot" where your dialog will end up and fade that in. Then use a (few) frame animation(s) to get the bounce effect.
More info here: Creating a Pop animation similar to the presentation of UIAlertView
To make it better than "not good" you could ...
create a UIView in a nib (easiest if the part of your code where you need the effect is already utilising a nib) and then add a translucent graphic (with a 'focus' effect) to that view.
connect the UIView in the nib to an IBOutlet
fade in the graphic using an animation into view hierarchy (omz example shows this)

Apply inner-shadow to UILabel [duplicate]

This question already has answers here:
Inner shadow effect on UIView layer?
(17 answers)
Closed 9 years ago.
I want to apply inner-shadow to a UILabel. I have a solution, but it's not good enough. Anyone with a better solution?
// UILabel subclass
- (void) drawTextInRect:(CGRect)rect {
CGSize myShadowOffset = CGSizeMake(0, 2);
float myColorValues[] = {255, 0, 0, 1};
CGContextRef myContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(myContext);
CGColorSpaceRef myColorSpace = CGColorSpaceCreateDeviceRGB();
CGColorRef myColor = CGColorCreate(myColorSpace, myColorValues);
CGContextSetShadowWithColor (myContext, myShadowOffset, 5, myColor);
CGContextSetBlendMode(myContext, kCGBlendModeLighten);
[super drawTextInRect:rect];
CGColorRelease(myColor);
CGColorSpaceRelease(myColorSpace);
CGContextRestoreGState(myContext);
}
I'm familiar with the layer property of UILabel, but shadow offset gives us a outer-shadow, NOT inner-shadow (unless i'm missing something).
Borrowing on Ruben's answer above, if you do the reverse ie. set your text color equal to your background color (with low alpha) and then set the shadow to be a stronger color, it creates a decent inset effect. Here's what I mean (Note: My view background is white):
cell.textLabel.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.5];
cell.textLabel.shadowColor = [UIColor darkGrayColor];
cell.textLabel.shadowOffset = CGSizeMake(-1.0,-1.0);
[cell.textLabel setText:#"Welcome to MyApp!"];
and this is the output
This would probably only work on very light backgrounds as I suspect it will create unwanted overlay on darker backgrounds.
You can ofcourse vary the shadowOffset to change the direction of light.
I tried to do this but finally opted to use the default shadowOffset and play with the shadowColor to give the inner drop shadow effect to the text. In small texts it gives you a good inner shadow effect. For example, if you have a grayColor background and apply a whiteColor to the shadow, then you have an acceptable inner shadow effect.
Sometimes, it's better to design those texts with graphic tools and make localized copies if needed.
Answer here : Inner Shadow in UILabel Long code but it seems to work

How to use a CGBlendMode on a UIView that scrolls above a fixed background?

Our main UIView is a UIScrollView with a fixed background image (very common, obviously). In that scrollView, we have several UIViews that hold content and scroll up and down as the user scrolls (also common). Those UIViews each have their own background, a simple gradient from white to black.
The goal is to have the background gradient of those (inner) UIViews be partially opaque AND use a CGBlendMode other than "kCGBlendModeNormal" (specifically, "kCGBlendModeOverlay"). You should be able to see through to the "parent" scrollView’s fixed background image as the UIViews scroll up and down above it.
- (void)drawRect:(CGRect)rect {
gradientStart = [UIColor colorWithRed:1 green:1 blue:1 alpha:1.0];
gradientEnd = [UIColor colorWithRed:0 green:0 blue:0 alpha:1.0];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[2] = { 0.0f, 1.0f };
NSArray *colors = [NSArray arrayWithObjects:(id)gradientStart.CGColor, (id)gradientEnd.CGColor, nil];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)colors, locations);
CGColorSpaceRelease(colorSpace);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetAlpha(context, 0.50); //this works!
CGContextSetBlendMode(context, kCGBlendModeOverlay); //doesn’t seem to do anything!
CGContextClearRect(context, rect);
CGPoint startPoint, endPoint;
startPoint.x = 0.0;
startPoint.y = 0.0;
endPoint.x = 0.0;
endPoint.y = rect.size.height;
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGGradientRelease(gradient);
[super drawRect:rect];
}
Everything works as expected except the CGContextSetBlendMode, which is ignored. We can't seem to find a way to change the blendMode of a UIView relative to what is behind it, the same way you can with alpha. Please note that this is different than building up multiple layers in a SINGLE UIView; in that case, this technique does change the blendMode of the layers "on top". We want to see through to the parent scrollView's fixed background image (as we scroll the child view up and down above it), with both an alpha and an overlay blend applied.
Here's an image showing the issue: http://img2.sbck.us/blendmode.png
Thanks in advance for your help!
I believe what you want is not possible with your current setup. On iOS, it is simply not possible for the blend mode of a view to have an effect on the stuff that is drawn under the view. You would have to draw the scroll view's background and the gradients in the same view.
This is possible, at least with two image views. It might even be possible with more general views. The approach is to implement drawRect in the parent view, and do as follows:
Determine the rect for the foreground view.
Convert the rect in the foreground view to a rect in the background view.
Begin a new graphics context.
Draw the background with the proper blend mode.
Draw the foreground with the proper blend mode.
Extract the image from the graphics context.
End the graphics context.
Use the extracted image accordingly.
This allows a foreground image to blend with a background image.
Seems like you could do this by setting the 'compositingFilter' property of your view's CALayer. The comment in CALayer.h says "A filter object used to composite the layer with its (possibly filtered) background. Default value is nil, which implies source-over compositing."
Alas, CoreImage which provides the filters is not (officially) available on iOS.
I guess your other alternative would be to use OpenGL. You could still use UIView with OpenGL after a fashion by rendering your UIView's into images which could then be used a textures.

Drop Shadow on UITextField text

Is it possible to add a shadow to the text in a UITextField?
As of 3.2, you can use the CALayer shadow properties.
_textField.layer.shadowOpacity = 1.0;
_textField.layer.shadowRadius = 0.0;
_textField.layer.shadowColor = [UIColor blackColor].CGColor;
_textField.layer.shadowOffset = CGSizeMake(0.0, -1.0);
I have a slightly different problem - I want a blurred shadow on a UILabel. Luckily, the solution to this turned out to be number (2) from Tyler
Here's my code :
- (void) drawTextInRect:(CGRect)rect {
CGSize myShadowOffset = CGSizeMake(4, -4);
CGFloat myColorValues[] = {0, 0, 0, .8};
CGContextRef myContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(myContext);
CGColorSpaceRef myColorSpace = CGColorSpaceCreateDeviceRGB();
CGColorRef myColor = CGColorCreate(myColorSpace, myColorValues);
CGContextSetShadowWithColor (myContext, myShadowOffset, 5, myColor);
[super drawTextInRect:rect];
CGColorRelease(myColor);
CGColorSpaceRelease(myColorSpace);
CGContextRestoreGState(myContext);
}
This is in a class that extends from UILabel and draws the text with a shadow down and to the right 4px, the shadow is grey at 80% opacity and is sightly blurred.
I think that Tyler's solution number 2 is a little better for performance than Tyler's number 1 - you're only dealing with one UILabel in the view and, assuming that you're not redrawing every frame, it's not a hit in rendering performance over a normal UILabel.
PS This code borrowed heavily from the Quartz 2D documentation
I don't think you get built-in support for text shadows here, the way you do with UILabel.
Two ideas:
(1) [Moderately tricky to code.] Add a second UITextField behind the original, at a very small offset (maybe by (0.2,0.8)? ). You can listen to every text change key-by-key by implementing the textField:shouldChangeCharactersInRange:replacementString: method in the UITextFieldDelegate protocol. Using that, you can update the lower text simultaneously. You could also make the lower text (the shadow text) gray, and even slightly blurry using the fact that fractionally-offset text rects appear blurry. Added: Oh yea, don't forget to set the top text field's background color to [UIColor clearColor] if you go with this idea.
(2) [Even more fun to code.] Subclass UITextField and override the drawRect: method. I haven't done this before, so I'll mention up front that this depends on this being the designated drawing method, and it may turn out that you have to override another drawing function, such as drawTextInRect:, which is specific to UITextField. Now set up the drawing context to draw shadows via the CGContextSetShadow functions, and call [super drawRect:rect];. Hopefully that works -- in case the original UITextField code clears the drawing context's shadow parameters, that idea is hosed, and you'll have to write the whole drawing code yourself, which I anti-recommend because of all the extras that come with UITextFields like copy-and-paste and kanji input in Japanese.
Although the method of applying the shadow directly to the UITextView will work, it's the wrong way to do this. By adding the shadow directly with a clear background color, all subviews will get the shadow, even the cursor.
The approach that should be used is with NSAttributedString.
NSMutableAttributedString* attString = [[NSMutableAttributedString alloc] initWithString:textView.text];
NSRange range = NSMakeRange(0, [attString length]);
[attString addAttribute:NSFontAttributeName value:textView.font range:range];
[attString addAttribute:NSForegroundColorAttributeName value:textView.textColor range:range];
NSShadow* shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor whiteColor];
shadow.shadowOffset = CGSizeMake(0.0f, 1.0f);
[attString addAttribute:NSShadowAttributeName value:shadow range:range];
textView.attributedText = attString;
However textView.attributedText is for iOS6. If you must support lower versions, you could use the following approach. (Dont forget to add #import <QuartzCore/QuartzCore.h>)
CALayer *textLayer = (CALayer *)[textView.layer.sublayers objectAtIndex:0];
textLayer.shadowColor = [UIColor whiteColor].CGColor;
textLayer.shadowOffset = CGSizeMake(0.0f, 1.0f);
textLayer.shadowOpacity = 1.0f;
textLayer.shadowRadius = 0.0f;

iPhone Layer confusion

I am trying to do something that should be really simple. I want to add a gradient to one of my views. I can add it to self.view, but not to viewWithGradient. Here is the code:
CAGradientLayer *gradient = [CAGradientLayer layer];
UIColor *colorFirst = [UIColor colorWithWhite:0.10 alpha:0.15];
UIColor *colorLast = [UIColor colorWithWhite:0.535 alpha:0.8];
NSArray *colors = [NSArray arrayWithObjects:(id)colorFirst.CGColor, colorLast.CGColor, nil];
gradient.colors = colors;
NSNumber *stopFirst = [NSNumber numberWithFloat:0.00];
NSNumber *stopLast = [NSNumber numberWithFloat:1.00];
NSArray *locations = [NSArray arrayWithObjects:stopFirst, stopLast, nil];
gradient.locations = locations;
gradient.frame = CGRectMake(0.0, viewWithGradient.frame.origin.y, viewWithGradient.frame.size.width, height_of_gradient);
[self.view.layer addSublayer:gradient]; // this works. I get a nice gradient at
// the bottom of the view, where I want it,
// but I need the gradient further down in
// my view hierarchy.
// [viewWithGradient.layer addSublayer:gradient]; // this doesn't. There
// is no visually noticeable change
// if this is uncommented and the
// above line is.
viewWithGradient is a small view inside my main view inside a viewController (self.view). There is only one other view over this viewWithGradient. It is a UILabel, that only takes up about one half of the area of viewWithGradient. It has a transparent background, but the label draws its text in white. I need to have the gradient be under the UILabel, not on self.view, over the UILabel.
I currently suspect that my frame/bounds may put the gradient offscreen. Does anyone see anything that I am missing? This seems like the simplest of the CALayer usages, and I have spent way too much time on it.
The y coordinate of your gradient's frame is viewWithGradient.frame.origin.y. Did you actually want 0? If viewWithGradient is more than halfway down the screen, your gradient will draw offscreen.