2
$\begingroup$

I have got a cube with 3 keyframes on frame 1, 24 and 48.

enter image description here

I want to scale the keyframes, but it scales from the center of the selected keyframes that is Frame 24.

enter image description here

How can I set the scaling to start from frame 1?

Here's the code I got.

import bpy

old_type = bpy.context.area.type
bpy.context.area.type = 'GRAPH_EDITOR'
bpy.ops.graph.interpolation_type(type='CONSTANT')
bpy.context.scene.frame_current = 1
bpy.ops.transform.resize(value=(2, 1, 1))
bpy.context.area.type = old_type
$\endgroup$
2
  • 1
    $\begingroup$ I would just move the keyframes as Jakemoyo says, but in your case you may try: bpy.ops.transform.resize(value=(2, 1, 1), center_override=(1, 0, 0)) $\endgroup$
    – alambre
    Apr 4, 2022 at 19:00
  • $\begingroup$ This works too. $\endgroup$ Apr 5, 2022 at 5:58

1 Answer 1

3
$\begingroup$

I think it makes a lot more sense to manipulate the keyframe data directly instead of using Python to simulate resizing them in the window. I have found that almost every time you find yourself trying to manually override the window context or something to execute a function there is probably a better way to do it.

import bpy

# get the active object
obj = bpy.context.active_object
# get the animation data and fcurves from the object
# the fcurves are a good way to get direct access to the keyframes
curves = obj.animation_data.action.fcurves

#loop over every fcurve
for c in curves:
    # get the keyframes for every fcurve
    keyframes = c.keyframe_points
    #loop over every keyframe and divide their x coordinate by a scale factor
    for kf in keyframes:
        #this is the number to scale by, 
        #if  you want to scale them all down by half then you'd divide by two
        scale_factor = 2.0
        # co is the keyframe's coordinate attribute
        # we only want to scale them on the x-axis (time) 
        # not on the y (amplitude)
        # /= is a shorthand for saying kf.co.x = kf.co.x / 2
        kf.co.x /= scale_factor

```
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .