如何从richtextbox获取像素颜色
问题描述:
on richTextBox(bachground color black and white forground)我写了一封来自richTextBox的字母y
我希望得到矩形尺寸为64X64像素的颜色。
问题,因为你可能会讨论我无法从richTextBox获取位图
见A行
我尝试过:
on richTextBox(bachground color black and white forground) i wrote letter y
from the richTextBox i want to get the color of the rectangle size 64X64 pixels.
the problem as you may gussed i could not get a bitmap from the richTextBox
see line A
What I have tried:
Color[,] pixelColor = new Color[100, 100];
//objMyBitMap = new Bitmap(640, //480,System.Drawing.Imaging.PixelFormat.Format24bppRgb);
Bitmap rtb = (Bitmap)richTextBox1.Clone();//<------- Line A
for (i = 1; i < 64+1; i++)
{
for (j = 1; j < 64+1; j++)
{
//pixelColor[i,j] = objMyBitMap.GetPixel(i, j);
pixelColor[i,j] = rtb.GetPixel(i, j);
}
}
答
您无法将控件转换为位图
。你必须做不同的事情:从控件的边界矩形复制屏幕的一部分。最有可能的是,您使用的是System.Windows.Forms
和System.Drawing
。如果是这样,你可以使用System.Drawing.Graphics.CopyFromScreen
:
Graphics.CopyFromScreen方法(Int32,Int32,Int32,Int32,大小)(System.Drawing) [ ^ ]。
要将部分屏幕复制到位图中,首先要创建一个所需大小的位图实例并获取的实例System.Drawing.Graphics
可用于在此位图中绘制: Graphics.FromImage方法(图像)(System.Drawing) [ ^ ]。
另一个问题是:GetPixel
非常慢。相反,你必须使用其中一种方法System.Drawing.Bitmap.LockBits
:
Bitmap.LockBits方法(Rectangle,ImageLockMode,PixelFormat)(System.Drawing) [ ^ ]。
关于预期结果的几句话:很明显,RTF文档在某种程度上没有自己的像素颜色。它的渲染取决于设备,边界矩形的当前布局,系统设置和其他细节。例如,如果您只使用白色背景的黑色文本,您将获得多种颜色,特别是抗锯齿和 ClearType 效果。这让我对你的问题的目的感到困惑。-SA
You cannot cast a control intoBitmap
. You have to do different thing: copy a part of the screen from the bounding rectangle of the control. Most likely, you are usingSystem.Windows.Forms
andSystem.Drawing
. If so, you can useSystem.Drawing.Graphics.CopyFromScreen
:
Graphics.CopyFromScreen Method (Int32, Int32, Int32, Int32, Size) (System.Drawing)[^].
To copy part of the screen into a bitmap, first create a bitmap instance of required size and obtain an instance ofSystem.Drawing.Graphics
which can be used to draw in this bitmap: Graphics.FromImage Method (Image) (System.Drawing)[^].
Another problem is:GetPixel
is prohibitively slow. Instead, you have to use one of the methodsSystem.Drawing.Bitmap.LockBits
:
Bitmap.LockBits Method (Rectangle, ImageLockMode, PixelFormat) (System.Drawing)[^].
Few words on the expected result: it's pretty obvious that RTF document, in a way, does not have its own pixel colors. Its rendering depends on the device, current layout of the bounding rectangle, system settings and other detail. If, say, you use just black text of white background, you will get several colors used for, in particular, anti-aliasing and ClearType effect. It makes me feel puzzled about the purpose of your question.—SA