I'm writing an iPhone app and I'm new to the iOS sdk. Heres what I'm trying to accomplish. I want an image to flash on top of my screen (On top meaning over everything that's already in my view). I could do this fine, but I want it to be semi-transparent so I'm assuming I need to use the quartz libraries.
I implemented these two functions in a UIView class. This code that works ok but it creates a black background around the image. I want just the image with no box background around it. Is there a CGContext function I can use to alter or remove the background? Should I not be calling drawRect? Am going completely in the wrong direction? Let me know if I anyone needs more information. Thanks.
// Implements UIView
-(void)drawInContextCGContextRef)context{
CGRect imageRect;
imageRect.origin = CGPointMake(8.0, 8.0);
imageRect.size = CGSizeMake(64.0, 64.0);
CGContextSetAlpha(context, 0.5);
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGContextDrawImage(context, imageRect, image);
}
-(void)drawRectCGRect)rect
{
[self drawInContext:UIGraphicsGetCurrentContext()];
}
Here's my code that calls it from the view controller.
[quartzUIView drawRect:CGRectMake(50, 50, 150, 250)];
[self.view addSubview:quartzUIView];
I think you're over-complicating it... No need to go low level.
You can use an UIImageView, just set its opacity to something you like (0.5f for instance) and be sure to set its opaque property to NO.
Related
So I am doing some custom animations on my navigationcontroller and the way it pushes and pops the viewControllers.
Everything runs smooth. As soon as I add the following code (In a subclass of UINavigationController), I face a huge performance hit. After adding a shadow all animations become very laggy. Is this expected or am I doing something wrong in the code?
// This code gets called once during NavigationController initialization.
[self.view setClipsToBounds:NO];
[self.view.layer setCornerRadius:5];
[self.view.layer setShadowOffset:CGSizeMake(0, 20)];
[self.view.layer setShadowColor:[[UIColor yellowColor] CGColor]];
[self.view.layer setShadowRadius:20.0];
[self.view.layer setShadowOpacity:1];
EDIT:
Changed my shadow radius to 1 and it's still slow
self.view.layer.shouldRasterize = YES;
self.view.layer.rasterizationScale = UIScreen.mainScreen.scale;
I was recently having some issues with slow CALayer shadows, and that simple line of code fixed up everything for me!
You should expect a slowdown from adding a shadow. A shadowRadius of 20 is very high and will be especially slow.
The other key to improve shadow rendering speed: set the shadowPath property. It can help dramatically.
Using shadowPath instead of shadowOffset.
theView.layer.shadowPath = [UIBezierPath bezierPathWithRect:theView.bounds].CGPath;
Check this post: iphone - Animation's performance is very poor when view's shadow is on
Yes, shadow's are very expensive (especially a shadow that big -- play with the radius and you'll notice it makes a huge difference in the degree of slowdown you experience). One way to improve performance is to render it once to a CGImageContext and just display that image instead of having the layer re-render the shadow every time it redraws (but this doesn't work if the shadow needs to animate or something).
Swift 5.3. add this code.
myView -> UIView, collectionViewCell or tableViewCell can be.
myview.layer.shadowPath = UIBezierPath(rect: cell.bounds).cgPath
myview.layer.shouldRasterize = true
myview.layer.rasterizationScale = UIScreen.main.scale
I'm coding app with "Neumorphism" style, so much shadow and app so laggy. But use this code below, app very smooth.
viewHasShadow.layer.shouldRasterize = true
viewHasShadow.layer.rasterizationScale = UIScreen.main.scale
I am perfoming image sequences animation is on main thread.
At the same time i want to take snapshot of device screen in back ground.
And by using that snapshots i want make video..
Thanks,
Keyur Prajapati
For taking the screenshots while running the image animations
use
[self.view.layer.presentationLayer renderInContext:UIGraphicsGetCurrentContext()];
instead of
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
it will take screenshots while runing animations
iOS uses Core Animation as the rendering system. Each UIView is backed by a CALayer. Each visible layer tree is backed by a presentation tree. The layer tree contains the object model values for each layer, i.e., values you set when you assign a value to a layer property (A and B). The presentation tree contains the values that are currently being presented to the user as an animation takes place (interpolated values between A and B).
If you're doing it in CoreAnimation you can render the layer contents into a bitmap using -renderInContext:. Have a look at Matt Longs Tutorial. It's for Objective-C on the Mac, but it can be easily converted for use on the iPhone.
Create one another thread where you can do this:
//Create rect portion for image if full screen then 320X480
CGRect contextRect = CGRectMake(0, 0, 320, 480);
// this is whate you need
UIGraphicsBeginImageContext(contextRect.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
viewImage is the image which you needed.
You can write this code in function which can be called timely bases like per 5 seconds or according to your requirements.
Hope this is what you needed.
I'm sure I'm missing something basic here. I'm trying out the CALayers 'hello world' code from:
http://www.raywenderlich.com/2502/introduction-to-calayers-tutorial
Doing the very first example. New single view project in xcode 4.2. No change to the nib/storyboard. Import QuartzCore. Add the following code to ViewDidLoad in the ViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.layer.backgroundColor = [UIColor blueColor].CGColor;
self.view.layer.cornerRadius = 30.0;
self.view.layer.frame = CGRectMake(20, 20, 20, 20);
}
I run this (ipad 2 or ipad simulator) and get a full screen blue rectangle with rounded corners. What I hoped to get was a 20x20 blue rectangle offset by 20/20.
I'm clearly getting control over the views layer (as shown by the color and rounded corners). However, adjusting the frame seems to have no impact. I've NSLog'ed the frame before/after setting it, and it has changed. Is the frame of the root layer locked to the uiview frame?
I don't have a strong reason to change the views layers frame, I'm just trying to reason through what is going on. Hopefully this is an easy question...
Thanks!
Paul
Actually, the previous answer (you can't set uiview.layer.frame as it always fills the uiview) is close, but not quite complete. After reading the answer, I registered for the original site and to comment that the tutorial had issues. In doing so, I found that there were already comments that I hadn't seen in my first pass that addressed this. Using those, I started doing some testing.
The bottom line, if you move the self.view.layer.frame setting code from viewDidLoad to viewWillAppear, it works fine. That means that you can change the frame of the root layer of a view. However, if you do it in viewDidLoad it will be undone later.
However, the previous answer is still pretty close. I NSLog'ed the frame of the root layer and the frame of the view. Changing the root layer frame changes the view frame. So, the answer that the view.layer.frame always fills the view.frame is correct. However, setting the layer frame resets the view frame to match. (I'm guessing that uiview.frame property simply returns uiview.layer.frame...)
So, at some point in time between 2010 and today, something in the environment changed. Specifically, after viewDidLoad and before viewWillAppear the uiview/layer frame appears to be reset to the nib specified value. This overrides any changes in viewDidLoad. Changes made in viewWillAppear appear to stick.
Robin's answer got me on the right track, but I wanted to spell out the full answer.
The tutorial is wrong. Setting the frame of the view's main layer has no effect. The main layer is 'special' and will always fill the view's bounds. What you need to do is create a sublayer of the main layer like this:
- (void)viewDidLoad
{
[super viewDidLoad];
CALayer *newLayer = [[CALayer alloc] init];
newLayer.backgroundColor = [UIColor orangeColor].CGColor;
newLayer.cornerRadius = 20.0;
newLayer.frame = CGRectMake(100.0f, 100.0f, 200.0f, 200.0f);
[self.view.layer addSublayer:newLayer];
[newLayer release]; // Assuming you're not using ARC
}
Also, in your code a layer with width 20pt and height 20pt is too small to have rounded corners of 30pt anyway.
Anyone ever seen the problem of [UIColor initWithPatternImage] ignoring the alpha values of the PNG? If so, what's the best fix?
I am using a png as a background layer to my array of button objects and it contains several pre-set alpha values per pixel in the image that is to be used as a texture background. It loads fine as a pattern/texture-color, but it comes up with all key transparent area as opaque black.
It is important that I get the right alpha values so that the button images shows correctly. The button frames do not include the alpha shadows from the background as that is not the "clickable" portion of the button. Additionally, my button object's images and background images also makes use of transparency, so it really needs to have a clear background directly behind each button to let the proper true current color settings come through (lowest layer UIView will have its background color set to the current user's selected color). Setting just the single alpha value for the UIView layer containing this texture does not work for my needs either.
Any help would be appreciated. My current workaround would be to use fully-blown, repeatedly-programmed layout of several UIImageView using the png, instead of a single UIView with the pattern fill.
Here is a snippet of code, but it's pretty standard for turning a UIImage into a UIColor for use as a pattern/texture color:
UIView *selectorView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,320)];
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"SelectorViewBackground.png"]];
selectorView.backgroundColor = background;
[mainView addSubview:selectorView]; // pattern background layer. Add UIButtons on top of this selectorView layer
[self addSubview:mainView]; // current user selected color set in mainView.
[selectorView release];
[background release];
I had the same problem with setting a background on a UIView with some transparancy,
this is how I solved it:
theView.backgroundColor = [UIColor clearColor];
theView.layer.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"the_image_with_transparancy.png"]].CGColor;
This is probably related to:
Tiled Background Image: Can I do that easily with UIImageView?
Basically, try setting:
[view setOpaque:NO];
[[view layer] setOpaque:NO];
No I've never had an issue with this. I use code like the above all the time for apps (though often I use it in conjunction with a layer instead of a view but that shouldn't make a difference with transparency being recognized) and always have had transparency work fine.
I'd look into your PNG file. I've noticed iOS sometimes being finicky with certain PNG options/types (like an 8 bit PNG with 8 bit transparency). Make sure your PNG is saved as 24 bit with 8 bit transparency (32 bit total).
Also, stupid question, but have you verified there isn't anything black in the view/layer hierarchy behind your PNG? Sometimes it's the stupid things like that
For those who might need the work-around code where the background patterns can be laid out as rows in a UIScrollView, here it is (adjusted to remove confidentiality concerns, should work if variables properly set prior to call).
Note that there should be ways to reuse just the one allocated instance of UIImageView multiple times to either save memory or load times but time-to-market is my No. 1 driver right now. Enjoy the journey :)
UIImageView *selectorView;
for (int i = 0; i < numRows; ++i) {
selectorView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"SelectorViewBackground.png"]];
selectorView.frame = CGRectMake(0, i * patternHeight, patternWidth, patternHeight);
[mainView addSubview:selectorView];
[selectorView release];
}
i was trying out quartz 2d today and i got to learn basic drawing and other things, but now, somehow everything i do doesn't draw a thing on the iphone screen! i tried making a new project and starting from scratch but still no luck... first, i made a new view based application, and then created a new file (.h and .m) as a subclass of UIView. In the implementation, i just overrode the drawRect method, and nothing happens! heres the code:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
CGContextSetStrokeColor(context, red);
CGContextBeginPath(context);
CGRect rectangle = CGRectMake(0, 0, 400, 200);
CGContextAddRect(context, rectangle);
CGContextSetFillColor(context, red);
CGContextFillPath(context);
}
i have another project that i started before and have the exact same code in and that runs perfectly... so i think i changed some settings or something.. can anyone help?
EDIT: there is nothing i forgot, im sure of it, since i've been doing what i did in my last project, but somehow, it doesnt draw in this one...
I usually forget to set the class of the custom view in Interface Builder (Class popup at the top of the Identity page of the Inspector window). That would explain why drawRect: isn't called.