[Asm] 纯文本查看 复制代码
import tkinter as tk
from tkinter import ttk
try:
from PIL import Image, ImageTk, ImageDraw, ImageFont
except ImportError:
try:
import Image, ImageTk, ImageDraw, ImageFont
except ImportError:
raise
from tkinter import filedialog, messagebox
from utils import safe_get_int, safe_get_float
import os
class PreviewManager:
def __init__(self, editor):
self.editor = editor
self.create_preview_area()
def create_preview_area(self):
self.preview_canvas = tk.Canvas(
self.editor.preview_container,
borderwidth=0,
relief="flat",
bg="#f0f0f0",
highlightthickness=0,
width=600,
height=800
)
self.preview_canvas.pack(fill=tk.BOTH, expand=True)
shadow_color = '#d0d0d0'
self.editor.preview_container.configure(style='Preview.TFrame')
style = ttk.Style()
style.configure('Preview.TFrame',
background=shadow_color,
relief='solid',
borderwidth=1)
self.preview_content = tk.Frame(
self.preview_canvas,
bg="white"
)
self.preview_canvas.create_window(
(0, 0),
window=self.preview_content,
anchor="nw",
width=600,
height=800
)
self.preview_canvas.bind('<Configure>', self._on_canvas_configure)
def upload_background(self):
file_path = filedialog.askopenfilename(
filetypes=[
("图片文件", "*.png *.jpg *.jpeg *.gif *.bmp")
]
)
if file_path:
try:
with Image.open(file_path) as img:
if img.size[0] <= 0 or img.size[1] <= 0:
raise ValueError("Invalid image dimensions")
self.editor.background_image_path = file_path
self.update_preview()
except Exception as e:
print(f"图片载错误: {e}")
messagebox.showerror("错误", "无法加载的图片,请选择其他图片。")
def update_preview(self):
self.preview_canvas.delete("all")
if self.editor.background_image_path:
try:
original_image = Image.open(self.editor.background_image_path)
canvas_width = 600
canvas_height = 800
width_ratio = canvas_width / original_image.width
height_ratio = canvas_height / original_image.height
scale_ratio = min(width_ratio, height_ratio)
new_width = int(original_image.width * scale_ratio)
new_height = int(original_image.height * scale_ratio)
x_offset = (canvas_width - new_width) // 2
y_offset = (canvas_height - new_height) // 2
resized_image = original_image.resize(
(new_width, new_height),
Image.Resampling.LANCZOS
)
self.background_photo = ImageTk.PhotoImage(resized_image)
self.preview_canvas.create_image(
x_offset, y_offset,
image=self.background_photo,
anchor="nw",
tags="background_image"
)
except Exception as e:
print(f"加载图片错误: {e}")
messagebox.showerror("错误", f"加载图片时出错: {e}")
header_text = self.editor.header_manager.header_text.get("1.0", tk.END).strip()
if header_text:
x = 300
y = safe_get_int(self.editor.header_manager.header_line_spacing, 20)
header_font = self.editor.header_manager.header_font
font_path = header_font[0]
font_size = header_font[1]
if isinstance(font_path, str) and font_path.lower().endswith(('.ttf', '.otf')):
try:
custom_font = ImageFont.truetype(font_path, font_size)
for line in header_text.split('\n'):
if line.strip():
temp_img = Image.new('RGBA', (1, 1), (0, 0, 0, 0))
temp_draw = ImageDraw.Draw(temp_img)
text_bbox = temp_draw.textbbox((0, 0), line, font=custom_font)
text_height = text_bbox[3] - text_bbox[1]
padding = max(40, int(text_height * 0.2))
img = Image.new('RGBA', (600, text_height + padding * 2), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
text_width = text_bbox[2] - text_bbox[0]
text_x = (600 - text_width) // 2
draw.text((text_x, padding), line, font=custom_font, fill=self.editor.header_manager.header_color)
text_photo = ImageTk.PhotoImage(img)
if not hasattr(self, 'text_photos'):
self.text_photos = []
self.text_photos.append(text_photo)
self.preview_canvas.create_image(0, y, image=text_photo, anchor="nw")
y += text_height + padding
except Exception as e:
print(f"自定义字体加载错误: {e}")
for line in header_text.split('\n'):
if line.strip():
self.preview_canvas.create_text(
x, y,
text=line,
font=("Arial", font_size, "bold"),
fill=self.editor.header_manager.header_color,
anchor="n"
)
bbox = self.preview_canvas.bbox(self.preview_canvas.find_all()[-1])
text_height = bbox[3] - bbox[1]
y += text_height
else:
for line in header_text.split('\n'):
if line.strip():
self.preview_canvas.create_text(
x, y,
text=line,
font=header_font,
fill=self.editor.header_manager.header_color,
anchor="n"
)
bbox = self.preview_canvas.bbox(self.preview_canvas.find_all()[-1])
text_height = bbox[3] - bbox[1]
y += text_height
y_position = y + safe_get_int(self.editor.header_manager.header_spacing, 50)
else:
y_position = 20
for section in self.editor.section_manager.sections:
title_text = section['title'].get()
if title_text:
x = 300
title_font = section['title_font']
font_path = title_font[0]
font_size = title_font[1]
if isinstance(font_path, str) and font_path.lower().endswith(('.ttf', '.otf')):
try:
custom_font = ImageFont.truetype(font_path, font_size)
# 创建临时图像(此处后续代码似乎未完整,原代码中此处应该还有后续操作,不过按照删除注释要求暂不考虑完整性问题)
except Exception as e:
print(f"自定义字体加载错误: {e}")