Moviepy教程:如何为视频叠加文本添加带描边的背景色
为MoviePy文本背景添加黑色描边
要给白色文本背景加上黑色描边,核心思路是在白色背景层的下方,叠加一层尺寸更大的黑色矩形作为描边,通过调整层级和位置让黑色矩形刚好露出一圈,形成描边效果。
以下是修改后的完整代码,关键改动已标注:
for step in data["steps"]: image_file = f"image{str(idx)}.png" # 替换为实际图片文件名 text1 = TextClip(wrap_text(step["text1"]), fontsize=48, color='black', font='Stanberry.ttf') text2 = TextClip(wrap_text(step["text2"]), fontsize=48, color='black', font='Stanberry.ttf') imageDuration = 5 videoDuration += imageDuration image = ImageClip(image_file).set_duration(imageDuration).resize(height=1920).resize(width=1080).margin(5, color=(0, 0, 0)) # --- 新增:创建黑色描边层,尺寸比白色背景大16(上下左右各8像素)--- stroke_size = 8 # 描边宽度,可按需调整 text1_stroke = ColorClip( size=(text1.size[0] + 20 + stroke_size*2, text1.size[1] + 20 + stroke_size*2), color=(0, 0, 0) ).set_duration(imageDuration) text2_stroke = ColorClip( size=(text2.size[0] + 20 + stroke_size*2, text2.size[1] + 20 + stroke_size*2), color=(0, 0, 0) ).set_duration(imageDuration) # --- 描边层创建结束 --- text1_bg = ColorClip(size=(text1.size[0] + 20, text1.size[1] + 20), color=(255, 255, 255)).set_duration(imageDuration) text2_bg = ColorClip(size=(text2.size[0] + 20, text2.size[1] + 20), color=(255, 255, 255)).set_duration(imageDuration) text1_pos = ('center', 50) text2_pos = ('center', image.size[1] - text2.size[1] - 50) text1 = text1.set_position(text1_pos).set_duration(imageDuration) text2 = text2.set_position(text2_pos).set_duration(imageDuration) # --- 调整描边层和背景层的位置,让描边刚好包裹白色背景 --- text1_stroke_pos = (image.w // 2 - text1.w // 2 - 10 - stroke_size, text1_pos[1] - 10 - stroke_size) text1_bg = text1_bg.set_position((image.w // 2 - text1.w // 2 - 10, text1_pos[1] - 10)) text2_stroke_pos = (image.w // 2 - text2.w // 2 - 10 - stroke_size, text2_pos[1] - 10 - stroke_size) text2_bg = text2_bg.set_position((image.w // 2 - text2.w // 2 - 10, text2_pos[1] - 10)) text1_stroke = text1_stroke.set_position(text1_stroke_pos) text2_stroke = text2_stroke.set_position(text2_stroke_pos) # --- 位置调整结束 --- # --- 调整合成顺序:底层图片 → 描边 → 白色背景 → 文本 --- composite = CompositeVideoClip( [image, text1_stroke, text1_bg, text1.set_start(0), text2_stroke, text2_bg, text2.set_start(0)], size=(1080, 1920) ) images.append(composite) idx += 1
关键说明:
- 描边宽度通过
stroke_size变量控制,可根据视觉需求调整数值(比如改成6或10) - 合成顺序必须严格遵循底层到上层:图片在最下方,接着是黑色描边,然后是白色背景,最后是文本,确保层级显示正确
- 描边层的位置需要比白色背景层往左上各偏移
stroke_size像素,保证黑色描边均匀包裹白色背景
内容的提问来源于stack exchange,提问作者kavaliero
相关产品推荐
相关产品推荐

