background image for CGContext - ios

Question: How do I display a background image underneath a CGContext?
I have created a view controller using the storyboard and placed a view with a full-screen background image. Then, using the same view controller, I created a outlet to a UIView that has a CGContext where I draw a few lines.
Everything works except that the drawing takes place underneath the background image. (Suddenly I wonder if it's not the CGContext but the UIView that is the problem.)
I found a similar question here, but the solution makes it sound like the background image has to be constantly refreshed using CGContextDrawImage with a CGImageRef. Which may be true, but a static image being constantly refreshed doesn't sound like a very elegant solution. Thank you!

Create custom UIImageView subclass where you will draw your custom background.
Better to subclass UIImageView instead of UIView, because in this case you don't get problems with adding other views above this in Interface Builder.
Add UIImageView to your view controller, and change class to your custom class. Add all other views above.

Question: How do I display a background image underneath a CGContext?
Answer: Set the color of the view with the CGContext to Clear Color.
That way the background image is visible as well as the lines that are subsequently drawn. Guess I kind of overcomplicated that one.
Thank you for the response Vitaliy.

Related

Curved View in IOS Swift

I am trying to create a view to implicate a swiping feature in a table view like the picture below.
I just want to curve one side of a view in equally to imply a swiping gesture. Is this easy to do in code? Or is it better to mask an image over the view? Please suggest.
Subclass UIView, implement the drawRect: method and do that shape (either by drawing to the context, or by using a bezierPath).
Make sure you set the view to opaque, and the backgroundColor to clearColor.

Custom UIView drawRect is called even with UIViewContentModeScaleAspectFill

I'm having the following issue.
Suppose I have my own image view class (to make it easy I've trimmed all the code and just included only the code that is causing the issue). That class inherits from UIView and overrides drawRect. Here is how my drawRect looks (the code is in Xamarin, but it's easy to understand)
public override void Draw(RectangleF rect)
{
base.Draw(rect);
CGContext context = UIGraphics.GetCurrentContext();
if (Image != null)
{
var imageRect = getAspectFillRect(rect, Image.Size);
context.DrawImage(imageRect, Image.CGImage);
}
else
{
this.BackgroundColor.SetFill();
context.FillRect(this.Bounds);
}
}
This code simply draws the image set to Image property in a way which simulates UIImageView's aspect fill option by calculating the rect which will display the image in aspect fill mode using this line of code getAspectFillRect(rect, Image.Size);
I also have UICollectionView with custom layout and custom cells. Each UICollectionViewCell UI is defined in an xib file, there I have all the necessary constraints set and I there I also have my custom view for displaying images. For that view in interface builder I've set content mode to "Aspect Fill". The custom UICollectionViewLayout is made in a way that cell expands (you'll see the example shortly). So the image inside the cell should also scale, and as I've set "Aspect Fill" option, it shouldn't call drawRect of my custom view, rather it should just scale already drawn content. But that is not the case!
LOOK HERE to see the video which demonstrates what happens.
You may see that the image inside is not growing together with the cell. The problem is that before ever the cell expanding animation begins drawRect of my custom UIView is called with the rect which will eventually be established after the animation. So I get a jerky animation. In my custom layout code I just call LayoutIfNeeded after updating the constraints of the cell. I don't call setNeedsDisplay, so I don't get why my drawRect is called.
For experiment I replaced my custom image view with UIImageView, I set it's content mode to "Aspect Fill", and LOOK HERE what happened. YEAH! It worked. So I suppose the issue is not in the custom UICollectionView layout, rather in my custom image drawing class.
What I should take into account?? How I should handle this case? Any Ideas?
Thanks!
DrawRect will be called whenever the system "feels" it should call it. Regardless if you call SetNeedsDisplay or not.
Now, setting ContentMode to ScaleAspectFill does not mean that DrawRect will not be called. In fact, from Apple docs here:
Instead of redrawing the contents of the view every time, you can use
this property to specify that you want to scale the contents (either
with or without distortion) or pin them to a particular spot on the
view.
This means that, if you don't want to go through the hassle of drawing the contents yourself, just set the ContentMode property. In your example, you are using DrawRect to draw.
Now, the fact that DrawRect is called before the animation starts, but with the target value for Bounds (or Frame?) means that the target value of these properties is set before the change finishes. During an animation, these properties do not change. Note during. A Bounds' or Frame's value will not change through all the values of an ongoing transition. It only knows "start" and "end".
What would happen in your app if DrawRect was not called before the animation start, but was called after animation end? Well, the cell would resize along with its subview, but your image would remain small throughout the animation and snap to the large size after the animation finished. So it's one way or the other.
Solutions:
Use the UIImageView.
If you do need to use a custom view, use a UIImageView on that to display your image.
Draw your image on a custom CALayer and add that layer on your custom view's Layer.

Make a UIButton background image larger than frame

I'm trying to make a UIButton with a background image where the image is larger than the button frame.
The problem is, the UIButton automatically scales the image to fit and haven't found a way to change the behavior.
Am I missing something obvious or is it time to make a custom button?
Subclass UIButton and override the
- (CGRect)backgroundRectForBounds:(CGRect)bounds;
method so it returns the size you want.
TIP: Use this method to center your background as well.
Looks like the answer to this one is. Not possible through existing interface on UIButton.
The simplest way to implement seems to be using a custom sub class of UIButton and creating a UIImageView with the same frame as the UIButton, turn off clipping and scaling and then just capture all the setBackground methods and capture state changes to handle "normal" button interaction changing the background images.

Drawing an overlay on a UIView

I have a UIView that I draw a CGPath to and would like to draw an overlay onto the entire view itself, one z level above the rendered CGPath.
How is this done? Should I use a layer? I would like to draw or fill parts of the view repeatedly, so I am not sure if it might be better to use some kind of fill method. Is there a more efficient way to fill parts of the view other than drawing a new path?
I want to create the effect similar to a progress bar, extending the overlays width during runtime depending on a value.
You could use a subview (or, similarly, a sub-layer) for this. A subview of a view will appear above the content rendered in drawRect:.
If you can get away with using a UIImage background (say, one created with resizableImageWithCapInsets:), and simply changing the size of that view over time, it will likely be more efficient than redrawing in drawRect:.

How do I set a centered or stretched background image?

I have universal app. In that app I need the background image to be centered or stretched. That way when I rotate the device or switch it the image displays correctly.
Here is my code in viewDidLoad:
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"tux.png"]]
Can anyone tell me how to accomplish this?
I think you can't easily make it centered with backgroundColor. You may:
Stretch it before setting the image as backgroundColor, see How to fill background image of an UIView.
Create a customized UIView subclass and draw the background image yourself by overriding drawRect: method;
Or add a UIImageView to you view as the background. See "UIView Class Reference: Alternatives to Subclassing":
Image-based backgrounds - For views that display relatively static content, consider using a UIImageView object with gesture recognizers instead of subclassing and drawing the image yourself. Alternatively, you can also use a generic UIView object and assign your image as the content of the view’s CALayer object.

Resources