logic font sample code

本文介绍了一个使用Delphi实现的自定义过程,该过程能够将指定的中英文文本以特定字体绘制到窗体上。通过调整字体高度、宽度等属性,可以灵活控制输出文字的外观。

procedure TForm1.DrawFont(ParentHandle: HWND; x, y, fw, fh: Integer; c: string);
var
  FLogFont          : tagLogFontA;      //逻辑字体--结构体类型
  hTempFont,
    hPrevFont       : HFONT;            //字体句柄
  hTempDC           : HDC;              //设备描述表或图形设备句柄
  TempString        : string;           //输出的文字
begin
  FLogFont.lfHeight := fh;              //字高
  FLogFont.lfWidth := fw;               //字宽
  FLogFont.lfWeight := 1;               //字体笔划粗细程度
  FLogFont.lfUnderline := 0;            //没有下划线
  FLogFont.lfStrikeOut := 0;            //没有删除线
  FLogFont.lfItalic := 0;               //斜体效果否
  FLogFont.lfCharSet := GB2312_CHARSET; //字符集
  FLogfont.lfEscapement := 0;           //倾斜度
  FLogFont.lfOrientation := 0;          //方向与倾斜度取值同
  FLogFont.lfFaceName := '宋体';        //字体名称
  hTempFont := CreateFontIndirect(FLogFont); //创建逻辑字体
  TempString := c;
  hTempDC := GetDc(ParentHandle);       //取得窗口的设备句柄
  hPrevFont := SelectObject(hTempDC, hTempFont);  //取出窗口设备的当前字体,并替换为新字体
  //SetTextColor(hTempDc, clRed);         //设置设备窗口的文字色彩
  TextOut(hTempDc, x, y, PChar(TempString), Length(TempString)); //输出文字
  SelectObject(hTempDc, hPrevFont);     //恢复原有淖痔?br>  DeleteObject(hTempFont);              //删除逻辑字体
  ReleaseDC(Handle, hTempDC);           //释放设备接口
end;

var
  I                 : Integer;
  s                 : WideString;
  Len               : Integer;
  p                 : Integer;
begin
  panel1.Width := 100;
  panel1.Height := 23;
  s := '中国人';
  len := length(s);
  p := panel1.Width div len;
  for i := 1 to len do
  begin
    if (ByteType(copy(s, i,1),1) = mbSingleByte) then
      drawFont(panel1.Handle, (i - 1) * p, 0, p, panel1.Height, copy(s, i, 1))
    else
      drawFont(panel1.Handle, (i - 1) * p, 0, p div 2, panel1.Height, copy(s, i,
        1)); //中文.
  end;

 

import time import sys import threading from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.uic import loadUi from datetime import datetime, timedelta import ctypes import numpy as np import pandas as pd import msvcrt import queue import matplotlib.pyplot as plt from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas sys.path.append(r"../../../") from ART_SCOPE_Lib.functions import Functions from ART_SCOPE_Lib.constants import * from ART_SCOPE_Lib.lib import * from ART_SCOPE_Lib.errors import check_for_error, ArtScopeError class MyWindows(QMainWindow): def __init__(self): super(MyWindows, self).__init__() loadUi('./fff1.ui', self) # 获取已有的 QLineEdit 控件的引用 self.minSampleRate = self.findChild(QLineEdit, 'minSampleRate') self.column_count_limit = self.findChild(QLineEdit, 'column_count_limit') self.acquisit_break = self.findChild(QLineEdit, 'acquisit_break') self.channel_number = self.findChild(QLineEdit, 'channel_number') # 初始化UI元素,设置默认值 self.minSampleRate.setText('50000') # 默认采样率为50000 self.acquisit_break.setText('30') # 默认采集时长为30秒 self.column_count_limit.setText('10') # 默认列计数器为10 self.channel_number.setText('1') # 默认通道1 # 获取已有的widget控件 self.widget_1 = self.findChild(QWidget, 'widget') # 获取ui文件中的widget控件 self.widget_2 = self.findChild(QWidget, 'widget_2') # 获取ui文件中的widget控件 # 创建matplotlib图形并嵌入widget控件 self.fig_1, self.ax_1, self.canvas_1 = self.embed_plot(self.widget_1) self.fig_2, self.ax_2, self.canvas_2 = self.embed_plot(self.widget_2) # 设置 matplotlib 使用的字体 plt.rcParams['font.sans-serif'] = ['SimSun', 'Microsoft YaHei'] # 使用宋体和微软雅黑 plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题 self.timer = None # 定义一个定时器 self.acquisit_2.clicked.connect(self.f_initial) self.acquisit_3.clicked.connect(self.f_data) def f_initial(self): try: print(type(self.channel_number.text())) self.min_sample_rate = int(self.minSampleRate.text()) # 获取采样率 self.column_count_limit = int(self.column_count_limit.text()) # 获取列计数限制 self.acquisit_break = int(self.acquisit_break.text()) # 获取采集时长 self.channel_number = int(self.channel_number.text()) # 设置通道数 print(self.channel_number) self.led2.setStyleSheet("QLabel { background-color: red }") time.sleep(0.2) except Exception as e: print(f"初始化失败: {e}") def f_begin(self): try: self.f_initial() self.min_sample_rate = int(self.min_sample_rate) # 获取采样率 self.column_count_limit = int(self.column_count_limit) # 获取列计数限制 self.acquisit_break = int(self.acquisit_break) # 获取采集时长 self.channel_number = int(self.channel_number) # 设置通道数 # 创建用于存放fft数据的队列 self.data_queue = queue.Queue() self.data_queue_2 = queue.Queue() # 创建第二个队列,用于数据保存 # 启动FFT和数据保存线程 self.fft_thread = threading.Thread(target=self.fft_logic) self.fft_thread.daemon = True # 设置为守护线程 self.fft_thread.start() self.data_flag = 1 self.column_count_flag = 1 self.data_thread = threading.Thread(target=self.data_logic) self.data_thread.daemon = True # 设置为守护线程 self.data_thread.start() # 在单独的线程中启动采集 self.acquisition_thread = threading.Thread(target=self.acquisition_logic) self.acquisition_thread.start() self.led2.setStyleSheet("QLabel { background-color: green }") except Exception as e: print(f"开始采集失败: {e}") def f_data(self): if self.timer is not None and self.timer.isActive(): return # 如果定时器还在运行,则不再执行 # 启动定时器,延迟1秒后执行代码 self.timer = QTimer(self) self.timer.setSingleShot(True) # 设置定时器为单次触发 self.timer.timeout.connect(self.handle_button_click) # 设置延时后的处理函数 self.timer.start(500) # 延时500毫秒(0.5秒) def handle_button_click(self): if self.data_flag: self.data_flag = 0 if not self.data_queue_2.empty(): x = self.data_queue_2.get() #清除队列2 print("停止保存") self.led2.setStyleSheet("QLabel {background-color: red}") else: self.column_count = 0 self.data_flag = 1 print("开始保存") self.led2.setStyleSheet("QLabel { background-color: green}") def acquisition_logic(self): try: taskName = 'Dev1' # 设备名称 taskHandle = lib_importer.task_handle(0) # 任务句柄 self.taskHandle_close = taskHandle # 创建任务 error_code = Functions.ArtScope_init(taskName, taskHandle) if error_code < 0: check_for_error(error_code) # 设置采集模式 acquisitionMode = SampleMode.CONTINUOUS error_code = Functions.ArtScope_ConfigureAcquisitionMode(taskHandle, acquisitionMode) self.data_queue = queue.Queue(maxsize=self.min_sample_rate * self.channel_number) self.data_queue_2 = queue.Queue(maxsize=self.min_sample_rate * self.channel_number) # 设置垂直参数 if self.channel_number == 1: channelName = '0' elif self.channel_number == 2: channelName = '0,1' elif self.channel_number == 3: channelName = '0,1,2' else: channelName = '0,1,2,3' # 通道名称 verticalRange = InputRange.RANGE_10VPP # 范围 verticalOffset = 0 # 偏移 verticalCoupling = CouplingType.DC # 耦合 probeAttenuation = 1 # 未使用 enabled = 1 # 通道启用 error_code = Functions.ArtScope_ConfigureVertical(taskHandle, channelName, verticalRange, verticalOffset, verticalCoupling, probeAttenuation, enabled) if error_code < 0: Functions.ArtScope_Close(taskHandle) check_for_error(error_code) # 设置水平参数 refPosition = 0 # 触发位置 error_code = Functions.ArtScope_ConfigureHorizontalTiming(taskHandle, self.min_sample_rate, self.min_sample_rate, refPosition) if error_code < 0: Functions.ArtScope_Close(taskHandle) check_for_error(error_code) # 设置软件触发 error_code = Functions.ArtScope_ConfigureTriggerSoftWare(taskHandle) # 获取实际通道数 numWfms = ctypes.c_uint32(0) error_code = Functions.ArtScope_ActualNumWfms(taskHandle, numWfms) if error_code < 0: Functions.ArtScope_Close(taskHandle) check_for_error(error_code) # 初始化采集 error_code = Functions.ArtScope_InitiateAcquisition(taskHandle) if error_code < 0: Functions.ArtScope_Close(taskHandle) check_for_error(error_code) # 获取实际样本长度 actualRecordLength = ctypes.c_uint32(0) error_code = Functions.ArtScope_ActualRecordLength(taskHandle, actualRecordLength) if error_code < 0: Functions.ArtScope_Close(taskHandle) check_for_error(error_code) # 数据缓冲区 sumLength = actualRecordLength.value * numWfms.value waveformPtr = np.zeros(self.min_sample_rate*self.channel_number, dtype=np.double) # 启动采集 error_code = Functions.ArtScope_StartAcquisition(taskHandle) if error_code < 0: Functions.ArtScope_ReleaseAcquisition(taskHandle) Functions.ArtScope_Close(taskHandle) check_for_error(error_code) timeout = 5.0 # 超时时间(单位:秒) readLength = actualRecordLength wfmInfo = ArtScope_wfmInfo() # 分析信息 wfmInfo.actualSamples = 0 wfmInfo.pAvailSampsPoints = 0 self.column_count = 0 # 采集循环 while True: error_code = Functions.ArtScope_FetchVoltage(taskHandle, timeout, readLength, waveformPtr, wfmInfo) if error_code < 0: Functions.ArtScope_StopAcquisition(taskHandle) Functions.ArtScope_Close(taskHandle) check_for_error(error_code) self.data_queue.put(waveformPtr[:self.min_sample_rate]) # 传到fft self.column_count = self.column_count + 1 if self.data_flag and self.column_count < self.column_count_limit: self.data_queue_2.put(waveformPtr[:]) # 传到保存队列 elif self.data_flag and self.column_count == self.column_count_limit: self.start_time = datetime.now() self.data_queue_2.put(waveformPtr[:]) # 传到保存队列 elif self.data_flag and self.column_count == self.acquisit_break: self.column_count = 0 except Exception as e: print(f"数据逻辑失败: {e}") def data_logic(self): try: df_auto = pd.DataFrame() while True: while self.data_flag: if not self.data_queue_2.empty(): df_auto[f"Waveform {self.column_count}"] = self.data_queue_2.get() # 将waveformPtr幅值给新的列 print(self.column_count) # 每column_count_limit个波形后保存数据 if self.column_count == self.column_count_limit: begin_time = (self.start_time- timedelta(seconds=self.column_count_limit)).strftime("%Y-%m-%d_%H-%M-%S") f_name = f"{begin_time}.xlsx" df_auto.to_excel(f_name, index=False) print(f"数据已保存到 {f_name}") df_auto = pd.DataFrame() except Exception as e: print(f"数据逻辑失败: {e}") def fft_logic(self): while True: if not self.data_queue.empty(): data = self.data_queue.get() self.ax_2.clear() time_axis = np.linspace(0, 1, self.min_sample_rate) # 创建时间轴,从 0 到 1 秒 self.ax_2.plot(time_axis, data[:self.min_sample_rate]) # 绘制时域信号 self.canvas_2.draw() # 更新显示 # 执行傅里叶变换 fft_result = np.fft.fft(data[:self.min_sample_rate]) fft_freq = np.fft.fftfreq(self.min_sample_rate, d=1.0 / self.min_sample_rate) # 计算频率 mask = (fft_freq >= 1000) & (fft_freq <= self.min_sample_rate / 2) filtered_fft_freq = fft_freq[mask] filtered_fft_result = np.abs(fft_result[mask]) # 更新图形 self.ax_1.clear() # 清除当前的图形 self.ax_1.plot(filtered_fft_freq, filtered_fft_result) self.canvas_1.draw() # 更新显示 time.sleep(0.1) # 短暂休眠,避免过度占用CPU def embed_plot(self, widget): # 初始化GUI绘图 try: self.fig, self.ax = plt.subplots() self.canvas = FigureCanvas(self.fig) layout = QVBoxLayout(widget) layout.addWidget(self.canvas) return self.fig, self.ax, self.canvas except Exception as e: print(f"嵌入绘图失败: {e}") def f_close(self): try: # 停止采集 self.led2.setStyleSheet("QLabel { background-color: red }") """ error_code = Functions.ArtScope_StopAcquisition(self.taskHandle_close) if error_code < 0: Functions.ArtScope_ReleaseAcquisition(self.taskHandle_close) Functions.ArtScope_Close(self.taskHandle_close) # 释放采集 error_code = Functions.ArtScope_ReleaseAcquisition(self.taskHandle_close) if error_code < 0: Functions.ArtScope_Close(self.taskHandle_close) # 关闭任务 error_code = Functions.ArtScope_Close(self.taskHandle_close) if error_code < 0: raise ArtScopeError("关闭任务失败") """ # 显示退出确认对话框 reply = QMessageBox.question(self, '退出', '确定要退出程序吗?',QMessageBox.Yes | QMessageBox.No,QMessageBox.No) if reply == QMessageBox.Yes: print("退出程序...") sys.exit() else: print("取消退出程序。") except Exception as e: print(f"关闭采集失败: {e}") if __name__ == '__main__': app = QApplication(sys.argv) window = MyWindows() window.show() sys.exit(app.exec_())
最新发布
06-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值