Unity简单实现调用电脑打印机打印图片功能

Unity简单实现调用电脑打印机打印图片功能

前言

因为我自己工作方面的原因,在实际的项目中开发过使用调用电脑打印机打印Unity程序中保存的图片的功能。我已经很久没有使用过这个功能了,但是今天忽然让测试下这个功能。于是很费劲地翻出以前的项目,实现了这一功能。很痛恨自己懒散,没有及时记录,今天加加班也要把这个记录到博客上哈哈。以下是实现步骤。

实现步骤

1.新建项目,在项目中新建一个名称为Plugins的文件夹,将System.Drawing.dll和User32.dll文件放进这个文件夹中,如下图所示:
在这里插入图片描述
2.在项目中新建StreamingAssets文件夹,将一张图片放入此文件夹中,如下图所示:
在这里插入图片描述3.开发打印Paint.cs脚本,此脚本的作用是开发打印基本功能,脚本开发完成后挂载到场景中,脚本代码如下所示:

using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using UnityEngine;
using System.IO;
using UnityEngine.SceneManagement;
using System;

public class Print : MonoBehaviour
{
    /// <summary>坐标X,Y</summary>
    private int coordinateX, coordinateY;
    /// <summary>图片的宽度和高度</summary>
    private int width, height;
    /// <summary>位图实例化</summary>
    private Bitmap bitmap;
    private System.Drawing.Printing.PrintDocument printDocument1;
    
    void Start()
    {
        coordinateX = 0;
        coordinateY = 0;
        width = 100;
        height = 100;
        this.printDocument1 = new System.Drawing.Printing.PrintDocument();

    }
    /// <summary>
    /// 设置打印信息
    /// </summary>
    private void SetPrintInfo()
    {
        this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDocument1_PrintPage);
    }
    private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
        e.Graphics.DrawImage(bitmap, coordinateX, coordinateY, width, height);
    }
    /// <summary>
    /// 开始打印列表
    /// </summary>
    public void StartPrintList(string path)
    {
        bitmap = new Bitmap(path);//根目录 
        SetPrintInfo();
        printDocument1.Print();
        //currentFile = null;
    }
}

4.开发调用打印功能脚本,开发完成后挂载到场景中的物体上,脚本代码如下所示:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ToDaYin : MonoBehaviour
{
    /// <summary>
    /// 文件名称
    /// </summary>
    public string pathName;
    //打印逻辑
    public Print print;

	// Use this for initialization
	void Start ()
    {
        pathName = Application.streamingAssetsPath + "/0.png";
        Debug.Log(pathName);
	}

    /// <summary>
    /// 打印
    /// </summary>
    public void ToDaYinThis()
    {
        print.StartPrintList(pathName);
    }

5.在场景中新建一个Button,将ToDaYinThis方法赋值到该button上,如下图所示:
在这里插入图片描述
6.打印效果如下所示,哈哈。因为打印了一张白色图片,所以什么也没有打印出来:
在这里插入图片描述

相关连接

工程源码

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 37
    评论
评论 37
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

波波斯维奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值