For as long as expressions have been around, expression writers have wanted a way to access a layer's color and alpha pixel data. There have been a few third-party solutions, but with the arrival of AE CS3, we now have an elegant and powerful way to get at this data. Here we're going to use this new tool to color some small animated layers based on the current underlying color of a background layer. We'll want the layers to pick up the color from their current position over the background layer.
We'll use solid, arrow-shaped layers to do the sampling. We'll animate these to wander around over the background layer using wiggle(). To each solid, we'll apply the Fill effect and apply our expression to the Color parameter of the effect.
We'll use the new layer method, sampleImage() to access the color data of the background image. It takes four parameters (the last two of which are optional). The first parameter specifies where (within the layer space of the layer being sampled) to extract the sample. Since we're going to be sampling a non-moving background layer which is the same size as the comp, its layer space is the same as comp space. That will allow use to simply use the comp position of the layers doing the sampling as the sample points.
The second parameter defines the sample area where color and alpha data will be averaged. Here we're going to average the color under our arrow layers, so we'll base the sample area on the width and height of our arrows. This parameter is a two-element array that specifies the horizontal and vertical distance from the center of the sample area to the edge. So in our case, we'll need to divide the width and height of our sampling layer by two.
The third parameter specifies whether to sample the color and alpha of a layer before or after masks and effects have been applied. This parameter defaults to true, which means the sampling is done after masks and effects have been applied.
The last parameter specifies when to take the sample. The default value for this parameter is the current comp time.
target = thisComp.layer("background"); target.sampleImage(transform.position, [width, height]/2, true, time)
Note that sampleImage() returns a standard four-element color value array, where the elements are red, green, blue, and alpha, and the value of each element ranges between zero and one. We didn't need this information for this example because we plugged the result directly into a parameter (Fill Color) that expected data in this format.
Although we defined a rectangular sampling area the size of our arrow layers, we're not always sampling the exact area under the layer. This is because the arrows rotate as they move around, but the rectangular sampling area we defined doesn't rotate.