«

用ROOT写一个EPS矢量图浏览器

时间:2021-12-23 21:17     作者:JourinTown     分类: 计算机技术


废话不多说,先上代码

#include "TROOT.h"
#include "TCanvas.h"
#include "TImage.h"
#include <iostream>
#include <fstream> 
void epsview(char ifl[256],double size=1.0)
{
   int length=0;char temp[256];int tp,h,l;
   for(int i=0;i<256;i++){if(ifl[i]=='\0'){length=i;break;}}
   if(length<5) {std::cout<<"invalid file name"; exit(0);}
   for(int i=length-4;i<length;i++){temp[i-length+4]=ifl[i];}temp[length]='\0';
   if(strcmp(temp,".eps")) {cout<<"not a eps file!"; exit(0);}
   std::ifstream op(ifl);
   op>>temp>>temp;
   op>>temp>>tp>>tp>>h>>l;
   std::cout<<"size:"<<h<<","<<l<<std::endl;
   TImage *ps = TImage::Open(ifl);
   if (!ps) {printf("GhostScript (gs) program must be installed\n");return;}
   new TCanvas("psexam", ifl, int(h*size), int(l*size));
   TPad *eps = new TPad("eps", "eps", 0., 0., 1., 1);
   eps->Draw();
   eps->cd();
   ps->Draw("xxx");
}

这个代码主要利用的是TImage对于postscript图片的解析,我们来分段理解一下这个代码吧

int length=0;char temp[256];int tp,h,l;
   for(int i=0;i<256;i++){if(ifl[i]=='\0'){length=i;break;}}
   if(length<5) {std::cout<<"invalid file name"; exit(0);}
   for(int i=length-4;i<length;i++){temp[i-length+4]=ifl[i];}temp[length]='\0';
   if(strcmp(temp,".eps")) {cout<<"not a eps file!"; exit(0);}

这里是通过循环得到输入字符串的长度,从而判断这个文件扩展名是否为eps文件

std::ifstream op(ifl);
   op>>temp>>temp;
   op>>temp>>tp>>tp>>h>>l;
   std::cout<<"size:"<<h<<","<<l<<std::endl;

一般来说,一个eps文件会在第二行的地方显示文件名和四角的(x1,y1,x2,y2)的位置,通过这样的方法就可以读到(x2,y2),从而得到这个eps的长宽比例,然后调用TCanvas时建立相同比例的canvas即可得到正确比例的eps文件了。后面绘图的部分应该是每个ROOT用户都熟悉的,这里就不多做解释了。

如果您想用一个简单的指令加在bashrc中以设为linux的一个eps查看器指令,可以这样做!

alias epsv='function func(){source ~/eps.sh $1;unset -f func;};func'
# eps.sh
root -l '/path/to/epsview.c("'$1'")'

像是这样设置的话,就可以在任何地方简简单单利用epsv xxx.eps就可以浏览eps文件了吗,其中第二句unset -f func;还可以用后就清理掉这个函数,使其不污染shell环境。

标签: ROOT EPS

版权所有:《豪言亂語
文章标题:《用ROOT写一个EPS矢量图浏览器
除非注明,文章均为 《豪言亂語》 原创
转载请注明本文短网址:https://article.benhaotang.cn/pc/25.html  [生成短网址]