Trying to draw a shadow using code from this question: How do I draw a shadow under a UIView?
I implement it in a UIView subclass as discussed, but when I try and use it using UIView *shadow = [[ShadowView alloc]initWithFrame:CGRectMake(100,100,100,100)]; I get only a black square, rather than something resembling shadow.
Am I missing something here?
I know this an ancient question, but I came across it via google as I was trying to do the same thing. So I thought I would post incase anyone else has the same problem. I finally discovered a fix after reading this tutorial: http://www.raywenderlich.com/2134/core-graphics-101-glossy-buttons
You need to either uncheck Opaque, and set the Background to Clear Color in IB.
OR as shown in the tutorial set them in initWithCoder
-(id) initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
self.opaque = NO;
self.backgroundColor = [UIColor clearColor];
}
return self;
}
Yup, you probably need to explicitly add an #import to the top of your class. I've had the same issue before and that fixed it. (Can't exactly explain why though)
Related
I'm trying to make a controller that will be similar to Control Center in iOS7. From WWDC session #226 I've learnt how to get blurred image with different effects
UIGraphicsBeginImageContextWithOptions(image.size, NULL, 0);
[view drawViewHierarchyInRect:rect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
lightImage = [newImage applyLightEffect];
So, in other words, we just capture some image (make screenshot), perform blur effect and use this blurred image for our needs.
But if you open control center above some dynamic content you'll notice that control center's blurred background is changing as well as content does.
Does anybody know how to replicate this behavior?
The only way I see it is to capture content and make blur effect with some interval (e.g. half a second). But it looks redundantly.
Here are ready solutions that I've found:
1. The most unexpected: Use UIToolBar
- (id) initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
[self setup];
}
return self;
}
- (id) initWithCoder:(NSCoder *)coder
{
if ((self = [super initWithCoder:coder]))
{
[self setup];
}
return self;
}
- (void) setup
{
if (iOS7OrLater)
{
self.opaque = NO;
self.backgroundColor = [UIColor clearColor];
UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:self.bounds];
toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
toolbar.barTintColor = self.tintColor;
[self insertSubview:toolbar atIndex:0];
}
}
UIToolbar can be used for this needs, bacuse it has his only build-in blur mechanism, and this mechanism is dynamic, what is good. But the bad thing is that in some reason it ignores colors and makes background looks irredeemably...
Update:
To avoid color breaking, do not use barTintColor. You also may change style of toolbar if you want dark styled blur (use UIBarStyleBlack).
2. FXBlurView.
Unlike toolbar it more positive, but it's dynamic mechanism is rare yet and in fact it can be used only for static background. (dynamic = NO).
In iOS8 we can implement blur effect on views using UIVisualEffect class.
You can use below code to apply blur effect on view.
UIVisualEffect *blurEffect;
blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *visualEffectView;
visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
visualEffectView.frame = MYview.bounds;
[MYview addSubview:visualEffectView];
I've found LiveFrost to be a great, and easy to integrate project for live blurring.
https://github.com/radi/LiveFrost/
You can use UIVisualEffect from storyboard.
Drag the Visual Effect With Blur on the storyboard. The desired effect can be achieved by setting alpha of the BACKGROUND COLOR. The subviews should be added to View of Visual Effect View and they are not affected by the background blur.
The Vibrancy effect must be selected in View options above.
See image:
Using navigation bar to provide blurring will not work on older devices running iOS 7. As they are running lighter version of iOS 7 with almost no t
I have a UIViewController which contains a label and button. I would like the background of the view to be transparent so I set it to clearColor and opaque = NO.
However, the view always displays a white background. How can I fix this?
Thanks.
Once a new view controller is pushed to the top of the stack, whatever is behind it gets hidden so you can adjust the alpha settings for that view but there's nothing to reveal behind it (so you will see white).
You need to use a UIView instead. I'd normally subclass UIView and customise it the way I want, then instantiate and add it as a subview whenever you need to use it:
-(id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:CGRectZero])
{
// Add your label and button here...
}
return self;
}
Sorry, I do not have enough rep to comment on Rog's answer, so I will post 'Another Answer'.
Try this code and see if it turns out well for you:
UIVIew *view = [[UIView alloc] init];
view.alpha = 0; // alpha 1.0 is opaque, alpha 0.5 is translucent and 0 is clear
Honestly, I have not tried that before as I do not require doing so. But when I drag a new UIView from the library, alpha option is in the properties.
Hope this helps.
I have my app on iPhone with a UIViewController with some stuff inside.. image, textbox, etc...
is there a way to draw a line or something like this using opengl directly inside the UIViewController?
thanks in advance
Are you sure about the OpenGL?
I believe it will be impossible to use OpenGL above regular views.
You might add a custom view (inherit from UIView) above all the other views and draw anything you want on that view.
This view should have a transparent background color.
In addition, if you want to interact with the other views (tap buttons, edit text views, scroll etc.) then you will have to implement the hitTest method in your custom view in order to pass the touch event to the views that are located under this one...
EDIT: Don't mess with the hitTest. Just uncheck the User Interaction Enabled in the XIB...
EDIT: Code sample:
#interface TransparentDrawingView : UIView {
CGPoint fromPoint;
CGPoint toPoint;
}
- (void)drawLineFrom:(CGPoint)from to:(CGPoint)to;
#end
#implementation TransparentDrawingView
- (void)initObject {
// Initialization code
[super setBackgroundColor:[UIColor clearColor]];
}
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
[self initObject];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aCoder {
if (self = [super initWithCoder:aCoder]) {
// Initialization code
[self initObject];
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
// Draw a line from 'fromPoint' to 'toPoint'
}
- (void)drawLineFrom:(CGPoint)from to:(CGPoint)to {
fromPoint = from;
toPoint = to;
// Refresh
[self setNeedsDisplay];
}
#end
First I think you should know responsibilities of UIView and UIViewController.
UIView is mainly responsible for drawing (override touchBegin, ToucheMove, etc.), animating, manage subviews, and handle event; UIViewController is mainly responsible for loading, unloading views etc.
So, you should 'draw' this line at your customized view (UIView), not view controller.
Second: If you only need to display some simple shapes or lines. I suggest you use UI controls and images. Even 'drawRect' is not recommended since it will cause more resources used. Surely OpenGL need much resources.
The answer is quite simple, you have to create a new class extending UIView, and override the drawRect function in order to draw (with Quartz...) your line. Use this method if you want gradient background as well.
I am also developping with Adobe Flex 4, and I notice that iPhone SDK has no Skin and Layout "patterns" like Flex 4 does (for instance, UIView could have a Skin (in a separate file..) and a Layout (horizontal, Vertical, Tile....)), for me that is a terrible lack!
Its something that the open source library Three20 tries to bring to the iPhone SDK.
I have subclassed UIImageView and tried to override drawRect so I could draw on top of the image using Quartz 2D. I know this is a dumb newbie question, but I'm not seeing what I did wrong. Here's the interface:
#import <UIKit/UIKit.h>
#interface UIImageViewCustom : UIImageView {
}
- (void)drawRect:(CGRect)rect;
#end
And the implementation:
#import "UIImageViewCustom.h"
#implementation UIImageViewCustom
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
}
return self;
}
- (void)drawRect:(CGRect)rect {
// do stuff
}
- (void)dealloc {
[super dealloc];
}
#end
I set a breakpoint on drawRect and it never hits, leading me to think it never gets called at all. Isn't it supposed to be called when the view first loads? Have I incorrectly overridden it?
It'll only get called if the view is visible, and dirty. Maybe the problem is in the code that creates the view, or in your Nib, if that's how you're creating it?
You'll also sometimes see breakpoints failing to get set properly if you're trying to debug a "Release" build.
I somehow missed the first time that you're subclassing UIImageView. From the docs:
Special Considerations
The UIImageView class is optimized to
draw its images to the display.
UIImageView will not call drawRect: in a
subclass. If your subclass needs
custom drawing code, it is recommended
you use UIView as the base class.
So there you have it. Given how easy it is to draw an image into your view using [UIImage drawInRect:], or by using CALayer, there's probably no good reason to subclass UIImageView anyway.
Try to add
Edit:
- (id)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
[self setClearsContextBeforeDrawing:YES];//add this line also
}
return self;
}
- (void)setNeedsDisplay{
[self setNeedsDisplayInRect:self.frame];
}
into your code.
hope this helps.
Thanks,
madhup
Not directly answering your question, but may solve your problem:
Why do this with a subclass of UIImageView? Subclassing can always be problematic, especially for classes that aren't designed to be subclassed--and I bet UIImageView isn't. If you just want to draw stuff on top of an image, then create a view with a transparent background, draw whatever you want, and place it directly over the image.
Depending on your specific case, it could make sense to use a UIButton with a background image instead of a UIImageView. You could even set userInteractionEnabled to NO and the result would be indistinguishable from a UIImageView.
In this case your UIButton subclass would simply include:
- (void)drawRect:(CGRect)rect
{
if (kSomethingSpecial) {
[self setBackgroundImage:[UIImage imageNamed:#"RedBackground.png"]
forState:UIControlStateNormal];
}
}
Disclaimer - I would only recommend this if you have plans to use the image as a button at least some of the time. I can't wholeheartedly endorse using a UIButton as a workaround for this drawRect behaviour in UIImageView, as I'm sure Apple has its reasons for writing their API this way, like Mark referenced.
I have a fullscreen background image that is tiled, i.e. it has to be reproduced a few times horizontally and vertically in order to make a big one. Like in the browsers on ugly home pages ;)
Is UIImageView my friend for this?
If I understand your question correctly you can use colorWithPatternImage: on UIColor then set the background color on a UIView.
If you must use a UIImageView you can do the same but whatever image you place in the image view will draw in front of the tiled image.
To get alpha to work with pattern image, make sure you have the following set:
view.backgroundColor = [UIColor colorWithPatternImage:aImage];
view.layer.opaque = NO;
In WWDC 2018 video session 219 - Image and Graphics Best Practices, Apple engineer explicitly recommends not to use the pattern color for tiling backgrounds:
I recommend not using patterned colors with a background color property on UIView. Instead, create a UIImageView. Assign your image to that image view. And use the functions on UIImageView to set your tiling parameters appropriately.
So the best and simplest way to create a tiled background would be like this:
imageView.image = image.resizableImage(withCapInsets: .zero, resizingMode: .tile)
Or even simpler, if you use asset catalog – select your pattern image asset and, in the Attributes inspector, enable Slicing (Horizontal/Vertical or both), set the insets to zero, and width/height to the dimensions of your image:
then simply assign this image to your image view (Interface Builder works, too), just don't forget to set the UIImageView's contentMode to .scaleToFill.
For years I used Bill Dudney's approach, but iOS 6 has a much better solution. And ... today I found a way to make this work on old versions of iOS too.
create the new class "UIImage+Tileable" (copy/paste source below)
import this in any class where you want a UIImageView with tileable image. It's a category, so it "upgrades" all your UIImage's into tileable ones, using standard Apple calls
when you want a "tiling" version of an image, call: "image = [image imageResizingModeTile]"
UIImage+Tileable.h
#import <UIKit/UIKit.h>
#interface UIImage (Tileable)
-(UIImage*) imageResizingModeTile;
#end
UIImage+Tileable.m
#import "UIImage+Tileable.h"
#implementation UIImage (Tileable)
-(UIImage*) imageResizingModeTile
{
float iOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
if( iOSVersion >= 6.0f )
{
return [self resizableImageWithCapInsets:UIEdgeInsetsZero resizingMode:UIImageResizingModeTile];
}
else
{
return [self resizableImageWithCapInsets:UIEdgeInsetsZero];
}
}
#end
I use a variation of #Rivera's solution:
Put the following in a UIView extension:
- (void)setColorPattern:(NSString *)imageName
{
[self setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:imageName]]];
}
Then you can set the background pattern in the storyboard/xib file:
As I really like Interface Builder I created this UIImageView subclass to apply tiled backgrounds:
#interface PETiledImageView : UIImageView
#end
#implementation PETiledImageView
- (void)awakeFromNib
{
[super awakeFromNib];
UIImage * imageToTile = self.image;
self.image = nil;
UIColor * tiledColor = [UIColor colorWithPatternImage:imageToTile];
self.backgroundColor = tiledColor;
}
#end
I tried overriding setImage: but it seems IB doesn't call it when decoding a Nib file.
Swift version of Daniel T's solution. You still need to set the keyPath value in IB. Of course you could be more careful unwrapping the Optional UIImage.
extension UIView {
var colorPattern:String {
get {
return "" // Not useful here.
}
set {
self.backgroundColor = UIColor(patternImage: UIImage(named:newValue)!)
}
}
}