I have a CALayer that displays static content. The user can dynamically pass a subrect of it's frame and I want is to dynamically restrict the visible part of it to that subrect. Remaining part should be black. What is the right way to do this?
Asked
Active
Viewed 43 times
2 Answers
0
From the apple documentation:
You should limit any drawing to the rectangle specified in the rect parameter.
Which seems to imply that the passed 'rect' is just a suggestion. It doesn't create it for you.
So if you pass in an accurate subrect, you should translate the context over by the x and y values you defined.
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()!
context.translateBy(x: rect.minX, y: rect.minY)
// Do your drawing here...
}

jake
- 1,226
- 8
- 14
-
Sorry, this is not I am looking for. Looking for a way to mask an area with transparent or black pixels – Deepak Sharma Jun 12 '19 at 15:24
-
@DeepakSharma Exactly. Why don't you just cover your layer with a black layer that is masked so as to have a transparent rectangular hole in it corresponding to your rect? What's the difficulty? – matt Jun 22 '19 at 00:12
-
@matt Can you tell me exactly how to do it? How do I specify the shape of the black layer? From my understanding, the shape of the black layer will need to be computed in every drawRect cycle. In every drawRect cycle, I will need to update or create a new shape layer and set it as a mask. Is that something you recommend? – Deepak Sharma Jun 25 '19 at 10:09
-
Layers do not have draw rect cycles. You just recalculate the mask each time the user gives you a subrect. You have not given any indication of what that means in your question. – matt Jun 25 '19 at 12:04
-
1I have explained many times how to punch a hole in a view, as here: https://stackoverflow.com/a/23452614/341994 If you want more precise advice, ask a more meaningful question. – matt Jun 25 '19 at 12:10
0
Create a new calayer with its frame rect equal to the user’s subrect and assign it as the mask layer for your static content layer. This will then only draw the masked area.

Darren Ford
- 856
- 5
- 10