Calayer to uiimage. I want to show a box with some border at the corners and black background with some opacity so hide the other view from the AVCaptureVideoPreviewLayer. my codes are var sublayer = CALayer() sublayer. contentsGravity = kCAGravityCenter } The image appears way bigger than myView. This is how I Get the Image from the UIImagePickerController, which seems to work good : I have a CALayer and I want to add to it a stretchable image. Is there another way? Or a workaround to the id cast? Full code: ViewController. layer In my CALayer i am trying to animate images but the animation layer is not showing up. how can I animate a CAlayer's bounds to progressively reveal an image? Ask Question Asked 12 years, 6 months ago. The CALayer renders fine as I can see its background color and corner radius, but the image will i'm trying to render UIImage from CALayer keeping shadows, but the resulting image is different from the image in CALayer, why? code override func viewDidLoad() { super. Instantiate a new CALayer. So UIView is basically, in a lot of ways, it's just some According to this answer by ldoogy, setting the drawsAsynchronously property of CALayer to true enables a Metal based renderer vastly improving performance. The I am trying to use CAShapeLayer to mask a CALayer in my iOS app as it takes a fraction of the CPU time to mask an image vs manually masking one in a bitmap context; When I have several dozen or more images layered over each other, the CAShapeLayer masked UIImageView is slow to move to my touch. How to set the background of a CALayer to be transparent without affecting the borders? 1. class CAShapeLayer: CALayer. Here is a step-by-step solution to convert a CALayer to a UIImage:. png")! I am able to set UIImage type as contents to CALayer reference by using [overlayLayer setContents:(id)[posterImage CGImage]] and then able to add some basic animation to the layer like rotation and opacity. I've stepped through the code in the debugger and I'm sure that the image is being loaded correctly. I want to add an image in between videos, just like smiley or clip art. I have two options: Have one CALayer per UIImage, move the CALayer to different views like so: view. But is there a way to omit the rendering to Image/CGContextRef and use the UIView/CALayer directly in OpenGL or GLKit, so that if updates happens in the view it will be reflected in OpenGL/GLKit?. Modified 12 years, 6 months ago. If you wish to add the image in its Sounds like you want to render your layer into a UIImage. Alternatively, if you're not using a custom CALayer Hi, I am currently working on an app, that detects a model warehouse using a 2D reference Image and ARKit. However it isn't doing anything. If your question is about creating CGImage s without using a UIImage, you can try looking into the following functions: I'm having some issues getting a UIImage I draw inside a CALayer to show up without it's blurriness. CGImage. I referred to Find assets in library - add to a AVMutableComposition - export = crash and also Apple's ALAssetLibrary. CGImage; CoreFoundation objets aren't managed by ARC. I use it as self. SwiftUI’s ImageRenderer class is able to render any SwiftUI view hierarchy into an image, which can then be saved, shared, or reused somehow else. This framework renders the SVG onto a CAShapeLayer which can then be added to a views sublayer to display the SVG. frame. In that case, the method below should do the trick. I got imges with various sizes and ratios. contents = UIImage(named: "IMG_3682. backgroundColor = [UIColor blueColor]. I created a single view application, copied the image "body. png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0. UIImageView is easier to use, and the resulting code is easier to read, so unless you need to do something that requires I think there was a similar question about a week ago: Mask does not work when capturing a uiview to a uiimage On iOS6 there is a problem capturing a UIView with the mask applied (btw, in iOS 7 it has been fixed): you capture the image but the mask is not applied. I have many UIImage instances. I'm using CALayers and doing everything programatically but still this sounds like something that should be trivial to but I can't get it to work. I am having a wicked time trying to get an image to show up in a CALayer. contents = image!. Which of these two actions will be iOS Core Animation Layer (CALayer, Layer) CALayer is responsible for a graphic/visualisation stuff - Basis for drawing(e. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company I want to center the image inside a CALayer. backgroundColor = UIColor. Overview. This was too slow. duration = 3 animation. setupView() } func import SwiftUI // It works on iPhone, iPad 13+ and macOS 10. Ask Question Asked 8 years, 7 months ago. You would need to deform the image what is not simple and may not be achievable by CAShapeLayers. The typical technique for updating is to set the layer's contents property. // Persistent root view we going to use // Touches can be also intercepted by subclassing it let viewRoot: UIView = UIView() // CALayer : This is "The One" // Can use any CALayer subclass let layerOne: CALayer = CALayer() // Binding to change "The One" geometry let CALayer or UIView backgroundColor UIImage on iOS 4. Listing 1 shows how to create a gradient layer containing four colors that are evenly I am trying to draw a pie chart with a segment array and an image in the center of each slice , I am have drawn the pie chart , but not able to add an image to the cashapelayer. Ask Question Asked 14 years, 2 months ago. It seems rather straight forward but I cannot get the image to render no matter what I do. Connect and share knowledge within a single location that is structured and easy to search. 2 and Swift 3] Quick answer: use CALayer. UIGraphicsBeginImageContextWithOptions(layer. So what difference are you pointing to? If you are having performance problems, use Instruments to measure. contents. As said earlier, JSON doesn't have an image object. Like the question says, I am trying to get an UIImage from the preview layer of the camera. imageWithRenderingMode(UIImageRenderingMode. Upon tapping a child node I am displaying a GIF image by creating animation using CALayer and loading it in diffuse. And it actually works but only if it's affine tranform. thx for your help! but I found that it doesn't I'm trying to understand how to apply CIFilter on a CALayer using the filter array property. Has anyone done this before? If you look at the docs in Xcode6 you will see that posterImage() returns a Unmanaged<CGImage>! (in Swift, in ObjC it returns a CGImageRef). Q&A for work. calayer; shadow; Share. Before writing this question, I've. It give better performances. Hot Network Questions What are the naming schemes used for geographical features in other planets/moons? Liability for I have an image (png) which must fill the entire screen of my app. What I have achieved till now looks like this: I know how to render a UIView/CALayer to a CGContextRef and a UIImage/CGImageRef. About; Products OverflowAI; Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, I'm having a problem with some code in the loadView: method of one of my view controllers. About; Products OverflowAI; Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide To get the images from the last one, I need to convert a CGImage to an UIImage, but I'm having trouble with that. does anyone what is max width and height [CALayer renderInContext] can handle on actual device (iphone retina or non-retina) before it crashes ? Share Follow Image-based backgrounds - For views that display relatively static content, consider using a UIImage View object with gesture recognizers instead of subclassing and drawing the image yourself. I'm creating my mask image programmatically. Figure 3 shows the layer at the What i tried was assigning each Rect its own CALayer and an UIImage. Viewed 2k times 0 Good day all; I am trying to manually (not using sublayers) draw images within a CATiledLayer but it is not behaving as it should with the defined solution. Animations are another way to make visible changes to a view without requiring you to subclass and implement complex drawing code. If you just want to show an image in a layer (let's suppose your file is named image. 2; Swift 2; My issue is that I cannot consistently center my CALayer. contentsGravity = kCAGravityResizeAspect; imageLayer. Smiley and Clip art most probably has animation. contents = (id)[[UIImage imageNamed:@"grayTrim. This is what I have tried. The code that draws the PDF (Tiled Layers) is located in: Android: Something similar to CALayer? Ask Question Asked 13 years, 8 months ago. Follow answered Sep 16, 2012 at 10:08. 3. Modified 4 years, 1 month ago. With over 6000 CALayers the result was very slow. Here is a step-by-step solution to convert a CALayer to a How does CALayer relate to UIView? UIView handles many things, including layout and touch events. Can you please tell me what is wrong, and if you also know the reason why it's wrong, that would a I'm using this code to convert CALayer to Data(taken from here) extension CALayer { /// Get `Data` representation Skip to main content. The example code: self. Also, it can hold bi-planar chroma subsampled images, which is very memory efficient. self. I am using this simple code snippet to render the view as an UIImage: If I pass in a UIImage it shows the image correctly on all faces. Or it might simply be a bug – you can report it to Apple via feedbackassistant. -drawRect:) with -[UIImage drawInRect:blendMode:alpha:] and the relevant CGContext If so, ultimately, it is going to call -[UIImage CGImage] on the UIImage and then pass that CGImage as the contents property of a CALayer. For anyone curious for the actual code: // assuming the view you're trying to darken is called 'mainUIView' // make the dark layer the same size as the view you're overlaying UIView *darkBackgroundView = [[UIView alloc] initWithFrame:mainUIView. Adding border to mask layer . Viewed 3k times Part of Mobile Development Collective 2 I'm going to port an iOS app to Android. Improve this answer . 0 NSCollectionViewItem selection on NSImageView, border around image with CALayer. Modified 14 years, 1 month ago. Community Bot. presentationLayer hitTest:location] modelLayer]; UIView *hitView = [hitLayer delegate]; This should be the view you can add your animating UIImageView to. A representation of a single layout constraint between two layers. I set the sublayer's contents property equal to a UIImage object that is created using a CGImageRef object called imageRef:. You use a gradient layer to create a color gradient containing an arbitrary number of colors. Follow edited May 23, 2017 at 11:56. How to add a border to a circular image with mask. For that I am showing a rectOfInterest with some CALayer for visual representation. This is the code I'm using to draw my UIImage: I'm using the following CALayer extension in my macOS app to render a CALayer into an image: extension CALayer { /// Get `Data` representation of the layer. origin, from: textView. UIImageView is no exception to that. The problem is Im not able to set the image size and even add CATiledLayer or CALayer drawing UIImage not working. I the following piece of code to accomplish this task: let cicontext = CIContext( Now, you're trying to treat Item as a JSON object judging from UserDefaults. 1 CALayer position animation on video layer. To use a filter, just drop the CI & lowercase the first letter of the name (e. Also if you do renderInContext on a view , all its subviews will be drawn onto the context. 0 Assigning UIImage to Collection View Cell. On how to store the images as JSON object, it depends on what those images are. Swift 3 and CGContextDrawImage. You could probably get it to work without one, but I wouldn't recommend it. I think this is because the origin is at the bottom-left instead of the top-left. saveItems you implemented, so it'd make sense for Item to be codable. 25, y: 0. Modified 13 years, 7 months ago. However, certain kinds of image processing operations, such as CoreImage filters, applied to I want to capture the contents of the portion of an MTKView that has most recently updated into an UIImageView. There are a number of different transforms you can do on a layer, but the basic ones are. The scale of this should mean that the resulting CALayer is relatively sharp, but it isn't. As for integrating your existing layer with the UIView, I'd create a subclass of UIView and override its +layerClass method to return the Class of your custom CALayer. import UIKit class ViewController: UIViewController { @IBOutlet var menuView: UIView! override func viewDidLoad() { super. Listing 1 shows how you can create a class named Layer Delegate that implements CALayer Delegate and sets it as a layer's (named import SwiftUI // It works on iPhone, iPad 13+ and macOS 10. Hi everyone, I would like to be able to save the content of a layer backed view and its CALayers to an image file, but I'm not sure how to access the data. If you wish to add the image in Listing 1 shows how you can use render(in:) to create a UIImage from a CAShape Layer with a path that describes a circle. Apple doc:. You can add an image to a view's layer simply by using its contents property: Yes, it is possible to create a UIImage from a CALayer (including its sublayers) in iOS development. It is 16x16 at 1x and 32x32 at 2x It is 16x16 at 1x and 32x32 at 2x The code is being called in the correct logical order: init , setImage: , setFrame ; I have an image called arrowWhite. Stack Overflow. contents = [UIImage imageWithData:imageData]; subLayer. 0 Background image for ios viewcontroller not working Creating a CALayer. For that version, I created a custom subclass of UITextField called "UnderlinedTextField". However, the image is presented in the color upside-down. What if I create a category on UIView (or CALayer) that adds a method along the lines of: I have a custom UIView that I want to render as an UIImage. 5); Figure 2 shows the layer created in Listing 1 resized to 400 x 400, 200 x 200 and 100 x 100 points. – I have created a CALayer (I added several shapes to the layer, but ultimately, I have a single CALayer), and I am having a LOT of trouble adding it to a CGImage. contents = UIImage(named: "star")?. I want to save all sublayer to one image in the photo library. Attached to my AVPlayer there is a CALayer that is used to display video on my UIView. apple. Follow edited May 23, 2017 at 12:33. Try this: var relativePosition = parentlayer. Obj-C. subLayer. When you receive an unmanaged object from an unannotated API, you should immediately convert it to a memory managed object before you work with it. 2 CALayer's image not showing up. translate (move) scale; rotate; To do transforms on a CALayer, you set the layer's transform property to a CATransform3D type. Follow edited The following method attempts to apply gausian blur to an image. render(in:) Alternatively, you can also use a generic UIView object and assign your image as the content of the view’s CALayer object. John John. png"]. in the first time the UIViewController loads it takes 2-3 seconds for the image to appear. size is correct, and layer. My problem is that the CALayer does not render its UIImage contents when the UIViewController becomes visible. y imglayer. On iOS 3 SDK, the following code worked fine in a CATiledLayer class: - (void)drawInContext:(CGContextRef)context { UIImage* image CALayer *layer = [[CALayer alloc]init]; layer. width, height: leftBGImage. ALwaysTemplate). -drawRect:) with -[UIImage drawInRect:blendMode:alpha:] and the relevant CGContext @IBOutlet weak var myView: UIView! var l: CALayer { return myView. I can't remember immediately whether initWithLayer: does that for you. sublayer throughout my view controller because I have made it a property in my view controller's header file. jpg")?. I'm placing a 400x300px image into a 123x89 CALayer. 280 sides). This allows me to navigate through a PDF much like the ibooks PDF reader. In other words - it is a Janina Kutyn: So CALayer is the fundamental object of the Core Animation framework. I will be moving them between views in a TableView situation. I have i custom UIView and i'm setting an image to the contents of a layer. Render the CALayer to a CGContext (Core Graphics Context): I don't have a definite answer but I'd guess that you'd see a slower load time when using UIImage than you'd see when using CGImage. Here is some example code: UIImage *image = [UIImage I am trying to create a QR Reader. Everything looks good in the views but when I save the CALayer, by converting it to a UIImage with UIGraphicsContext and using UIImageWriteToSavedPhotosAlbum, I only get one layer saved. That is old news. You can find blending modes here CICategoryCompositeOperation. 16. Viewed 3k times Part of Mobile Development Collective 5 For certain reasons, I'm trying to avoid using a CAScrollLayer to do this. Asking for help, clarification, or responding to other answers. contents = UIImage(named: "right_challenge_bg")?. But when I use it as a mask the whole screen becomes white. The code that draws the PDF (Tiled Layers) is located in: I am trying to use CALayer to display an image, but the image is not showing up. 13 Add CALayer below UIView. The OP was trying to add the underline using a CALayer, so that is how I originally implemented the solution. This allows you to manipulate the layer and I am working on an AR application in which I am rendering a 3D model. a. Just like Apple creates that You seem to slightly misunderstand pointers. png") let layer = CALayer layer. Is there any way to rotate a UIImage 90º and then add it to a UIImageView? I've tried a lot of different codes but none worked Thanks! Skip to main content. When I sue a simple CALayer I get what I get above. This means that later changing the address of square does not also modify contents. contentsCenter = CGRect (x: 0. Any hint? thank you When I sue a simple CALayer I get what I get above. Swift Add transparent color to UIImageView background. I would like to generate a UIImage from this Listing 1 shows how you can use render(in:) to create a UIImage from a CAShape Layer with a path that describes a circle. addSublayer(imgLayer) Have one CALayer per view, and replace the layer's contents with the UIImage as in viewLayer. size. cgImage Note that the UIImage needs to be converted to a CGImage. AirPods 4 AirPods Max AirPods Pro Apple Black Friday Apple Deals Apple Pay Apple Pro Display XDR Apple Studio Display I have a simple, single-view app and for some reason I cannot get a CALayer to display in the app's UIView. So I'm wondering, in general, is it a better idea to use CALayers and such, or just do all that stuff in photoshop and use UIImage(View)s for whatever I need? Scrolling performance How can we fill a shape layer with image in iOS using swift 4 ? I have tried using below. let animation : CAKeyframeAnimation = createGIFAnimation(url: gifImageURL!)! let layer = The image used is created using -[UIImage initWithContentsOfData:] and cached in the viewController. (See comments: my details were wrong) Per the UIImage documentation for -[UIImage CGImage]: If the UIImage object was initialized using a CIImage object, the value of the property is NULL. Front Page. The only way I can make the CALayer to render the UIImage is by setting its contents to the UIImage after the UIViewController is made visible, such as in the viewDidAppear: method. Content gravity is meaningful only for a layer with content, e. 7 Add a CALayer sublayer centered over UIImageView I've often read that using a CALayer rather than a UIImageView is an performance boost when it comes to heavy image usage. I've managed to get the effect with a still image using a CALayer, masking it with a triangle CAShapeLayer then replicating it with CAReplicatorLayer. uiImage { // use the rendered image somehow } I can to add a rotate animation to my CALayer but the main problem is the CALayer doesn't rotate during the rotation of my iPad – Alex Commented Jul 15, 2011 at 16:21 Example Basics. Instead, you could either convert your CIImage into a UIImage and display that in a UIImageView. Here's an example where contentsGravity matters; same image, same layer size, different content gravity: I have used colorWithPatternImage successfully to create a background color in a CALayer I am using for the background of a presentation. Those sublayers have multiple CABasicAnimation added to them. [NOTE: updated to Swift 2. Each test repeatedly allocs a view, adds it to the view hierarchy and then removes it and releases it. Essentially I have a view which centres itself in a larger view (on an iPad) and has some labels, buttons i wants to add a uiview insdie my CAlayer,i tried and I don't get correct answer,help me. 1 Add and Center image inside CALayer. Won't help with your question, Updated for Xcode 16. I fixed this by handling the case when a nil UIImage is returned from my Although most views use a plain CALayer behind them, there are specialized subclasses that do more advanced things. Improved in iOS 16. I have a related SO question here. The background color of the view is correct but the image in the CALayer is not visible. For example: Erasing part of a bezier path would be tricky you'd probably need to calculate intersections (of the stroke width, not just of the path itself) and break existing lines into multiple segments. So that you can change it to an image. You can create a CALayer instance as follows: import UIKit let myLayer = CALayer() You can also associate a CALayer with a view by setting the view’s layer property. I don't want to use a CALayer for every Image, i would end up with 20 000 CALayers or more So how to put together an "image" of images in a CALayer ? (which is then used as a sublayer) Code example: // rootView which is a Multiple CALayer borders on UIImage. 0 How to add color over CALayer() with alpha value? 1 SWIFT - CALayer between PNG and background image. Please share your ideas. background = [UIImage imageNamed: @"Background. However, when I display this CALayer, all transparency is lost. How to apply multiple I am using multiple CALayer's in my application with large UIImage as contents. frame]; CALayer *darkenLayer = darkBackgroundView. Now i am looking for a way not to use that much CALayer. The filters you can add to a CALayer will apply to the layer's content, so they can't be used to display your own content (your CIImage) on the layer. Methods that allow an object to manage the layout of a layer and its sublayers. It can contains sublayers which create CALayer hierarchy. At its simplest, the code needed is this: let renderer = ImageRenderer(content: Text("Hello, world!")) if let uiImage = renderer. I understand from hours of reading posts and the docs that this is because of the reverse screen coordinates. That's what CGLayer does, too. So ist there a mechanism to assign UIImages their own Rect inside a CALayer ? Slow / bad code Example: I wrote the following minimalistic iPhone app for drawing a simple png file onto a CALayer object. had experience with Affine transforms for views; read the Transforms documentation in the Quartz 2D Programming Guide; seen this detailed CALayer tutorial; downloaded and run the LayerPlayer project from Github; However, I'm still having trouble understanding how to do basic transforms on a layer. How to add a blur mask with a custom shape above a dynamic camera view in Swift? 3. contents = (id) image. To create a UIImage from a CALayer try Todd Yandell's solution: UIImage from CALayer - iPhone SDK. layer. thx for your help! but I found that it doesn't I was trying to set a UIImage's CGImage as a layer's content and then add the layer to a view's layer. mask = mask leftBGImage. I undertand that when you call 'CGContextDrawImage' you CALayer *hitLayer = [[flyingBird. com FWIW, you can view the CALayer tree using the 'Show Layers' option in Xcode's "Editor" menu while using the view debugger. Now I stuck at the point, How to save image locally [UIImage imageNamed:@"info. /// /// - Parameters: /// - fileType: The format of file. Like for example, clips to bounds versus masks to bounds and a lot of functions like that. Make sure that the timer fires the method on the main thread using one of the performSelectorOnMainThread methods. contents is a valid CABackingStore. After creating the layer, the code creates a CGContext into which the circle is rendered. But it seems the center of the stars is I have a sequence of images that I want to animate (UIImageView supports some basic animation but it's not sufficient for my needs). 0, 15 An image view is a CALayer. From the documentation: - drawInContext: The default implementation of this method does not doing any drawing itself. You need to call blurFilterMask once layout has completed and the final size of heroImageView is known. cgImage as Any mask. But for a video stream this is not the best approach since UIImageView is not made for handling so many frames per second. [UIImage imageNamed:@"info. Note that the UIImage needs to be converted to a CGImage. I want to colour this image to black. After some investigation from the docs I found this:. The app has a part, in which an UIImageView's image is composed dynamically from various CALayers. . With CGImage, you specify the image type (jpg or png) during creation, but with UIImage, the object type needs to be determined dynamically. Render the CALayer to a CGContext (Core Graphics Context): CoreFoundation objets aren't managed by ARC. but could not get any ideas to complete my requirement. – LastMove iOS 13, Swift 5. CODE: var buttonImage: UIImage = UIImage(named: "circleArrow")! override func layoutSubviews() { super. As explained in CAShapeLayer Class Reference, a CAShapeLayer is used for drawing shapes using a custom path. But initWithLayer: is how [NOTE: updated to Swift 2. That makes sense, because UIImageView causes 3 copies of the image in memory, which is needed for Core Animation. How could I achieve that? The only thing I found is a CALayer. So the idea was to put UIImage that should be transformed to UIImageView, apply 3d transform to it and save it's transformed content. This webpage affirms Idoogy's claim. swift. viewDidLoad() Well, a CGImage isn't a CALayer, so you are obviously leaving some steps out there, but I assume you know what you're talking about, as far as drawing to a CALayer or whatnot. Creating a CALayer is straightforward, as it’s part of the Core Animation framework, which is included in UIKit. In general, UIView objects are fairly thin wrappers around CALayers. convert(textView. func attachDropDownArrow() -> NSMutableAttributedString { let image:UIImage = UIImage(named: "arrowWhite. The display(_:) delegate method is called when the layer is marked for its content to be reloaded, typically initiated by the set Needs Display() method. contents = I have a CALayer with many sublayers. Now I want to get a UIImage from the video playing (when I push a button for the moment). height) leftBGImage. viewDidLoad() setUpLayer() } func setUpLayer() { l. Before you If you're using a CALayer as a mask for another CALayer, you can invert the mask by creating a large opaque layer and subtracting out the mask shape with the xor blend mode. The render tree is made of layers. contents = (id) [UIImage imageNamed:@"image. So I am asking myself: is the animation not working because I use c# or did I write something wrong? Can somebody help me with this, please? This is the function I wrote: public static void addFadeOverlayAtTheBeginning (NSUrl source, String overlay, long I'm probably just missing something really simple but whenever I add CALayers after the view is visible they don't render. I want to animate it to have no contents (no image), but continue showing the sublayers. bounds = CGRectMake(0, 0, 952, 650); frontLayer. contents = uiImage. About; Products OverflowAI ; Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or As I understand it, you are creating CALayer in the background, and adding that layer to the UI hierarchy in the background as well. If you are drawing it manually, I would probably switch to a I'm not sure what you mean by a "CALayer bezier path" but you have a couple of options here:Create a subclass of UIView, where you draw your circle using UIBezierPath methods in the drawRect:. So, I would expect a CALayer backed by a let buttonImage = UIImage (named: "button. answered Jun 1, 2013 I'm trying to create a kaleidoscope in iOS (I'm aware there is a CIKaleidoscope filter but it doesn't give me the sort of effect I'm looking for so I was hoping to roll my own). That method will add the CABasicAnimation to the layer. I got an Black background. And change color of different part of SVG Image. the code I use to create the l The part of the view that I want to render can't be predetermined, meaning I can't set up the view hierarchy for the small section to be it's own UIView (and therefore CALayer). Improve this answer. protocol CALayout Manager. build { let myLayer = CALayer() let animation = CAKeyframeAnimation(keyPath: "contents") animation. I am adding images in CALayer, but after playing around 20 times i get memory leak issue due to images which are been added to CALayer. For example, to translate a layer, you would do something like this: func configureMask(button:UIButton, with image:UIImage!){ A mask is an area, in our case a CALayer, where its opacity determines visibility to an underlying layer. It will draw your view's layer on the context. I am making a puzzle game, where in i have 35 cubes added on my screen. Add a comment | 1 Answer Sorted by: Reset to I don't think you can specify the blend mode used for compositing a CALayer or UIView (in particular, I suspect the "old" graphics hardware of the iPhone 3G doesn't support it; not sure about the 3G S). Color blending works between UIViews or CALayers. For this purpose, I'd use initWithLayer: rather than creating your own copy method. contents does not render image data. I have checked the layer's background colour (opacity has no effect on images set using contents) and it seems correct. 1. ios - How to render CALayer in context with positioning. Finding explanations and I'm trying to draw a bunch of preloaded images in a UIView's CALayer, but whenever the image displays, the app's memory usage spikes and the memory is not reclaimed whenever the image changes. Adding Transforms to a CALayer (translate, rotate, scale) Creating a CALayer ; Creating particles with CAEmitterLayer ; Disable Animations ; Emitter View with custom image ; How to add a UIImage to a CALayer ; Rounded corners ; Shadows ; Got any iOS Question? Ask any iOS Questions and Get Instant Answers from ChatGPT AI: ChatGPT class CAGradientLayer: CALayer. Figure 2 Layer with defined contents center at different sizes. This is how I Get the Image from the I have a CALayer and I want to add to it a stretchable image. If you can identify the image with something else, like a name, Core Animation doesn't know about UIKit, i. 0 How to set a tiled background image for a CALayer? 0 CALayer background color. Here is the code #import #import @interface Got a tip for us? Let us know. My first approach was to use UIImageView and set the image property when the image. However, it doesn’t directly control drawing or animations. You can specify the blend mode when doing custom drawing (e. Hot Network Questions How many follow-up emails should I send to professors Finally I combine a color and the UIImage to create a new UIImage that I can apply directly as a pattern. I know I can either capture a still image or use the outputsamplebuffer but my session quality video is set to photo so either of these 2 aproaches are I have a CALayer object called sublayer. It is 16x16 at 1x and 32x32 at 2x It is 16x16 at 1x and 32x32 at 2x The code is being called in the correct logical order: init , setImage: , setFrame ; I would like to tile a CGImage across a CALayer, but it seems to only want to stretch it. But in my case I don't use Core Animation. add UIImage in CALayer and Display an image or UIImage with a plain CALayer. I'm in need of an UIImage from a Masked CALayer. The key is setting the compositingFilter property on the appropriate CALayer (the one on top - it blends with whatever is behind it). If not, just keep on keeping on. " You may also need to create copies of the sublayers. I have found some references to [CALayer renderInContext:ctx], but I am not sure how to implement it. The effect I'm going after is to progressively reveal (from bottom to top) a CALayer's let mask = CAShapeLayer() mask. Create mask layer for UIView using CAShapeLayer() 3. class CAConstraint Layout Manager. 0 add UIView overlay to UIIMagePickerController video recording. values = let mask = CALayer() mask. Draw UIImage in a CALayer. However, I do not see any performance difference when drawsAsynchronously is set to true or false. Modified 14 years, 2 months ago. cgImage layer. You'll have to be careful with the end positions as when the animation finishes, your I have a CALayer with an image in it, and it has several sublayers. There is no way to apply CATransform3D to UIImage or CGImage or CIImage. Roundups. CGImage l. nschmidt nschmidt. fillMode = kCAFillModeForwards; Swift UIImage from CALayer crash. 2 How to set an image into an NSCollectionView? 0 Janina Kutyn: For UIView with the CALayer, even a lot of the properties on the view actually are just wrappers around properties on CALayer, and they just forward directly to the CALayer without even adding any action. For example, this code subtracts a I'm trying to render a UIImage in Objective-C (working on a simple iPhone app (breakout-type thing) to get used to the environment). How to add a UIImage to a CALayer. So CALayer is sort of the simpler, lower-level version of UIView that is not a part of the responder chain, because it's not a subclass of UIResponder. 1 How to add gradient colour to CALayer() Load 7 more related questions Presumably you mean animate rotating a UIImage around a full 360°? In my experience, the way to accomplish a full circle rotation is to chain multiple animations together: In my experience, the way to accomplish a full circle rotation is to chain multiple animations together: I currently have a view and I would like to change it into a UIImage. How to mask and add shadow to a UIView. However I do not get anything. I don't think you can specify the blend mode used for compositing a CALayer or UIView (in particular, I suspect the "old" graphics hardware of the iPhone 3G doesn't support it; not sure about the 3G S). Maybe only the top level ones. # How to add a UIImage to a CALayer. Now, I'd like to render the whole layer subtree to the UIImage at a specific point of animation time. 2,395 16 16 silver badges 22 22 bronze badges. Yes, it is possible to create a UIImage from a CALayer (including its sublayers) in iOS development. frame = CGRect(x: relativePosition. CIDivideBlendMode It's confusing as to what your view hierarchy actually is. In order to respond to user interaction, the best way is to use a UIView. Send us an email b. You can do this by overriding Please give ideas for how to crop UIImage on oval shape or circle shape. What I have achieved till now looks like this: Yes, it is possible to create a UIImage from a CALayer (including its sublayers) in iOS development. CGImage; then you add the layer as sublayer to the view something like: assume you in the view [self. How to draw NSImage to CGContext. I used svg image in iOS. height - relativePosition. This view can then be added to another view as a subview and animated using standard methods. UIKit delegates that task to the Core Animation framework, which You can also set the contents property of a CALayer to a CGImage or UIImage, allowing you to display images or other visual content: let myLayer = CALayer() myLayer. Anonymous form. There are up to 30 of these views on screen and on an iPad 2 the performance of animations along the perimeterPath (which is the path attribute of the perimeterLayer) was suffering. toValue = [NSNull null]; backgroundOut. unfortunately, when I don't need the layer nor the image - the memory is not freed. For the timer, create an NSTimer. That's what I want it to be. I get CALayer using SVGKLayeredImageView. The shape will be drawn antialiased, and whenever possible it will be mapped into screen space before being rasterized to preserve resolution independence. 5. fillMode = kCAFillModeForwards animation. To manually push a context to UIKit, use UIGraphicsPushContext() and pop it using UIGraphicsPopContext() when done. Inside this view, I am rendering some UI elements (drawing a bunch of circles over the image). They are independent pointers even if they point to the same address. contents by following this thread Set contents of CALayer to animated GIF?. An object that manages image-based content and allows you to perform animations on that content. Ask Question Asked 7 years ago. initWithLayer: is explicitly for creating "shadow copies of layers, for example, for the presentationLayer method. Why is this happening? and how can i fix it. How can I assign a UIImage (or its image data) to a CALayer and then display it? Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. UIImageView is easier to use, and the resulting code is easier to read, so unless you need to do something that requires Adding layers is very similar as adding subviews: layer. layer; // class CALayer. Mask layers are CALayers embedded in another CALayers. How do i put together/draw an Image with holes/transparent spots and draw that in a CALayer so the background is still visible. I refered to the following post Swift: Add image to CAShapeLayer, but it did not solve my issue. Cubes have four sides each (i. By default, the colors are spread uniformly across the layer, but you can optionally specify locations for control over the color positions through the gradient. 12 Relationship between UIVIew and CALayer regarding background image on iOS. I am trying to set a "tinted" version UIImage to CALayer content property, but it resulted in the original image instead. Set the back side layer transform to the same flipped transform you're animating to. The reason for the poor speed was due to the drawing of the images (which surprised me; I assumed the bottle neck would add UIImage in CALayer. Here self is a Shapelayer where i am going to set an Image let image = UIImage You seem to slightly misunderstand pointers. 1 1 1 silver badge. contents = (id) [UIImage imageWithData:imageData]; subLayer. I want to mask an image using CALayer and UIImage. mask = mask // Where layer is your CALayer // This also works for other CAShapeLayers Share. I'm programming in Swift. I don't want to use a CALayer for every Image, i would end up with 20 000 CALayers or more So how to put together an "image" of images in a CALayer ? (which is then used as a sublayer) Code example: // rootView which is a I was trying to capture and save an image of the splash screen inside application:didFinishLaunchingWithOptions: using the following code: UIWindow *w = [[[UIApplication sharedApplication] windows] My subclass of UIView makes extensive use of sublayers to build a complex image. borders, shadows, gradients, and so on). I'm trying to display a UIImage selected from a UIImagePickerController inside a subclass of CALayer and add it to my superview but I can't get it to work. I've verified that 'image' is not nil, image. Viewed 699 times 1 I am trying to add two different border layers to my image. contents = buttonImage?. 0, 15 I play a video with AVPlayer. So my code above was trying to create an UIImageView with a frame based on the sized of a nil UIImage thus causing it to crash. My understanding is that drawInContext is there to be overridden, whereas renderInContext is used to render the contents of a layer to the context. I am not sure how to change the texture coordinates. The shape is composited between the layer's contents and its first sublayer. layer addSublayer:layer]; Now I want to load an array of image as animation so eventually I will get the images animated. Would it be reasonable to think that all UI modifications are to happen in the main thread? If so, try this: let qualityOfServiceClass = QOS_CLASS_BACKGROUND let backgroundQueue = Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. 25, width: 0. var imageLayer = CALayer(); imageLayer. Dose anyone know how to convert multiple sublayers in a CALayer to a UIImage? I have a CALayer object into which I would like to insert a UIImage equipped with an alpha map, simply by setting the layer's contents property. Is like if I didn't get any image, because when I use the UIImage later, the app crashes with this log: *** Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan 653]' There is no purpose in setting the content gravity of a CAShapeLayer, as it will in no way affect how the shape is drawn. frame = CGRect(x: 0, y: 0, width: leftBGImage. clearColor(). png"] is being used elsewhere in the code and actually shows and image. It works ok. 2,694 2 2 gold badges 25 25 silver badges 30 30 bronze badges. But initWithLayer: is how CALayer Related Examples. - (void) I have already tried this solution CGImage (or UIImage) from a CALayer. Updated for Xcode 16. Setting an image as its contents will simply be ignored. According to the documentation this should be available from iOS5. How would you capture the contents of a You can use renderInContext on any CALayer. and I want to fit Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. About; Products OverflowAI; Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide Masking an image in Swift using CALayer and UIImage. So, I tried this code which I discovered after hours of reading Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company In general, UIView objects are fairly thin wrappers around CALayers. size, NO, 0); You can add an image to a view's layer simply by using its contents property: myView. content, corner radius, shadow [About], transforms ) and animations. I would like to do this because the UIImage class is much better for what I need to do. So it doesn't handle the As far as I know, the easiest way to do it is to add two sublayers representing the front side and the back side of the page. 5, height: 0. Provide details and share your research! But avoid . Solid areas appear, areas with an alpha of zero disappear. The goal is to detect what color of item UIImage and NSImage now automatically support reading ISO HDR images. My Idea I had an idea, but I need some direction if I'm going to succeed. uiImage { // use the rendered image somehow } Draw UIImage in a CALayer. CGImage; Note I am not using ARC, and after I remove the layer from its superlayer I release it (it is retained by a property). class CAConstraint. let layer = CALayer() let drawsAsynchronously = CAShapeLayer is good for masking, but your needs are more than just masking. CALayer - How do I create an image with a solid background and transparent text? 3. CGColor subLayer. The created mask image is a UIImage and works fine when I view it on its own. You can add an image to a view's layer simply by using its contents property: myView. layer } override func viewDidLoad() { super. 9. 1 Positioning content in a CALayer. Timings are taken from the start of loadView to viewDidAppear and given as fps (effectively, view draws per second). Share. let maskLayer = CALayer() Next, set its It looks like the x position is correct, but the y is off. x, y: relativePosition. 15+, yep with UIView. y, width: I have a Paging UIScrollView with a contentSize large enough to hold a number of small UIScrollViews for zooming, The viewForZoomingInScrollView is a viewController that holds a CALayer for drawing a PDF page onto. I do this with code from another question: UIImage from CALayer - Drawing a UIImage into CALayer. But my requirement is to add Gif Image View with animation to parentLayer CALayer? How do i put together/draw an Image with holes/transparent spots and draw that in a CALayer so the background is still visible. The fact that the memory seems to get reclaimed with a CALayer - How do I create an image with a solid background and transparent text? 3. Preloading of the images is done by reading them through UIImage 's facilities, rendering them onto a Bitmap Context and extracting a CGImageRef out Is there any way to rotate a UIImage 90º and then add it to a UIImageView? I've tried a lot of different codes but none worked Thanks! Skip to main content. png" in the bundle, and defined a UIView subclass: I expect this method to add a layer displayi For this you'll need a CABasicAnimation. CALayer *hitLayer = [[flyingBird. But my requirement is to add Gif Image View with animation to parentLayer CALayer? Although the documentation doesn't say that CALayers work similarly to CGLayers, the Graphics and Imaging Overview says that Core Animation is “GPU-accelerated”, which I think we can safely interpret as saying that it puts CALayer content on the video card whenever it can. addSublayer(salamLogo) But in your case may be better to work with subviews? I do not see any purpose of using layers here. The custom UIView is a subclass of UIImageView. viewDidLoad() // Do any additional setup after loading the view, typically The issue is that when viewDidLoad is called the layout has not been done yet so your measurements are being taken from the initial state of the view controller , most likely from the storyboard size if thats what you are using. 25. png), you can use a CALayer and set I'm trying to display a UIImage selected from a UIImagePickerController inside a subclass of CALayer and add it to my superview but I can't get it to work. Follow edited Jul 14, 2021 at UIImage from CALayer in iOS. png), you can use a CALayer and set I created a little project (Github link) demonstrating how to add a line under a UITextField to answer this SO question. size); [layer I have a Paging UIScrollView with a contentSize large enough to hold a number of small UIScrollViews for zooming, The viewForZoomingInScrollView is a viewController that holds a CALayer for drawing a PDF page onto. I think there was a similar question about a week ago: Mask does not work when capturing a uiview to a uiimage On iOS6 there is a problem capturing a UIView with the mask applied (btw, in iOS 7 it has been fixed): you capture the image but the mask is not applied. A layer merely manages the state information surrounding a bitmap Is it possible to draw an existing png image inside a CALayer? If not, how can I have the image as a sublayer of a CALayer? I'm porting a CALayer from OS X to iOS. ColorSync, This image type is useful because, for example, it can be used as the contents of a CALayer. After rendering, UIGraphics Get Image From Current Image Context() generates the image. Basically, the important thing about it is that every UIView is backed by a CALayer. This is my code so far. Alternatively, you can also use a generic UIView object and assign your image as the content of the view’s CALayer object. contents = (id)[UIImage Teams. y = size. If the layer’s delegate implements the Discussion. Viewed 2k times 2 Good day all; I am not sure what has changed to prevent this from working. Skip to main content. Most of the "heavy lifting" of decoding and displaying the image is done by the CALayer in both cases, so I doubt if you'll see much difference. The answer to this question was forward progress and brings me to the issue I am having now. - (void) Draw UIImage in a CALayer. NSImageView transparency. Learn more about Teams I'm noticing that some of the things that I do with images in my app, I could be doing with CALayer properties instead (i. asked Jul 30, 2012 at 15:25. It's should be five stars at the center of the yellow view. // Persistent root view we going to use // Touches can be also intercepted by subclassing it let viewRoot: UIView = UIView() // CALayer : This is "The One" // Can use any CALayer subclass let layerOne: CALayer = CALayer() // Binding to change "The One" geometry let There might be restriction on whether that layer can be rendered for debugging purposes. If I just do: _layer. or to create a UIImage from a UIView try Tommy's solution: How to capture UIView to UIImage without loss of quality on retina display. CGColor; Most of the posts I read about animations and CALayer create an animation within a UIView. g. e. What i am doing wrong in here: return CALayer(). 0 Programmatically adding UIImage into collection view cell. masksToBounds = true Share. My idea is to get an UIImage from CALayer during video is playing. path = path // Where path is some CGPath layer. Is there any functionality to add UIImages and UIImage* image = [UIImage imageNamed:@"imageName"]; frontLayer = [CALayer layer]; frontLayer. Admittedly, this is probably as simple as looking at the first few bytes I am able to set UIImage type as contents to CALayer reference by using [overlayLayer setContents:(id)[posterImage CGImage]] and then able to add some basic animation to the layer like rotation and opacity. contents = image; Also, I know the sublayer is setup properly because if I add this statement it will turn the sublayer completely blue when I take a photo: subLayer. When you first assign contents = square contents is a copy of the pointer address (not an object copy). layer) relativePosition. The drawInRect: method in UIImage draws the image on this current context. png"]; [documentDisplay. Hot Network Questions How many follow-up emails should I send to professors I have a UIViewController with a UIImageView (imageView), and I'm defining several layers that will be nested in the imageview as follows in viewDidLoad: Try using renderInContext in place of drawInContext. a CGImage that is drawn into its contents property. This is the function I use: - (UIImage *)imageFromLayer:(CALayer *)layer { UIGraphicsBeginImageContext([layer frame]. Even the image size must be modified accordingly and color of image should also be tinted. 2. You can achieve this by rendering the CALayer into a CGImage and then creating a UIImage from that CGImage. Just add this to your view or controller class, or create a category on CALayer. Viewed 2k times 3 I am using PocketSVG framework in order to render SVG images. Here is another approach - not sure if it will work for you, but might be worth considering: The "Drawing" layers are probably what you already have. How to release the previous memory which is consumed by the older images added in CALayer. 0. Listing 1 Creating an image of a circle I am new in SVG Image usage. Modified 8 years, 7 months ago. However, I'm getting an "Error: CGContextDrawImage: invalid con Xcode 7. You say a UIImage in a UIView, do you mean you have a UIImageView inside a UIView?Or are you overriding drawRect to draw the image manually? I would look at insertLayer:atIndex: as you need to make sure your gradient is behind the image layer. Multiple CALayer borders on UIImage. The hosting view doesn't appear to be aware of any layer content, because when I created a pdf, using: NSData *data = [imageView dataWithPDFInsideRec: [imageView bounds]]; I am trying to create a QR Reader. The number of circles added can go up to the order of thousands. This code does not work: CABasicAnimation *backgroundOut = [CABasicAnimation animationWithKeyPath:@"contents"]; backgroundOut. An object that The reason for this is when users load in photos from their photo library, if there isn't enough memory to load the photo in, then nil will be returned for the UIImage. layoutSubviews() self. CATiledLayer is responsible for tiling images in the way you see in the Maps app, CAEmitterLayer handles creating particles, CAGradientLayer draws color gradients, and more – there’s a selection depending on your need. drawInContext: doesn't set the CALayer context as UIKit's current context. Here's the code I'm using: [[imageLayers objectAtIndex:0] removeFromSupe I had to do something like this. Set both the sublayers' doubleSided property to NO. ARC only works with Objective-C objets and does not implicitly know how to transfer the ownership when casting from (or to) an non-object pointer type. That custom subclass creates and maintains a Getting image data back from CALayer. I'm now trying to animate the . ycwlqd hekvnc zgiouj wokqo ubdelmj xdirhcb wtj qeczi yjstr bewlvj