由於,想在量測介面(CDialog)中,做出相似色、相反色、指定色、灰階(RGB同值)控制,所以將MFC內建的COLORREF和一些相對應的功能做進來。
CColorRef.h
#ifndef CCOLORREF_H
#define CCOLORREF_H
class ColorRef
{
COLORREF m_color;
public:
ColorRef();
ColorRef(const int&, const int&, const int&);
ColorRef(const COLORREF& clr);
ColorRef(const ColorRef& clr);
//彩色
void iRGB(const int&, const int&, const int&);
const COLORREF oRGB() const;
const unsigned char R() const;
const unsigned char G() const;
const unsigned char B() const;
//變色
const COLORREF Shift(int shift = 55) const;
const COLORREF Invrt() const;
//灰階
void iGray(const int&);
//運算子
public: void operator= (const ColorRef& clr);
const BOOL operator==(const ColorRef& clr) const;
private: void checkColor(const int& r, const int& g, const int& b) const;
const BOOL checkInv(const int&) const;
};
#endif
CColorRef.cpp
防禦性設計
當賦值時,要先經過這個函數做檢查,檢查完的值 確定安全,才儲存在物件中的記憶體空間void ColorRef::checkColor(const int& r, const int& g, const int& b) const
{
ASSERT(r >= 0); ASSERT(r < 256);
ASSERT(g >= 0); ASSERT(g < 256);
ASSERT(b >= 0); ASSERT(b < 256);
}
//應用的一些例子
ColorRef::ColorRef(const int& r, const int& g, const int& b):m_color(r, g, b)
{ checkColor(R(), G(), B()); };
ColorRef::ColorRef(const COLORREF& clrR):m_color(clrR)
{ checkColor(R(), G(), B()); };
ColorRef::ColorRef(const ColorRef& clr):m_color(clr.m_color)
{ checkColor(R(), G(), B()); }
void ColorRef::iRGB(const int& r, const int& g, const int& b)
{
checkColor(r, g, b);
m_color = RGB(r, g, b);
}
void ColorRef::iGray(const int& gray)
{
checkColor(gray, gray, gray);
m_color = RGB(gray, gray, gray);
}
相反色的設計
顏色相反要RGB個別與255相減。但是,會遇見一個問題,顏色在中間帶,進行相反色運算,會得到相似色。 所以在這一個「中間區段」相反色必須要換另一種算法,顏色的呈現,才會有大的對比(這也是要使用相反色的原意)。 在此的例子是使用130(這個值,可以自訂)。const COLORREF ColorRef::Invrt() const
{
const int r = ( checkInv(R()) )?(130 - R()):(255 - R());
const int g = ( checkInv(G()) )?(130 - G()):(255 - G());
const int b = ( checkInv(B()) )?(130 - B()):(255 - B());
return RGB(r, g, b);
}
checkInv是用來檢查,這個值是否在中間帶上。
const BOOL ColorRef::checkInv(const int& subclr) const
{
const int BandWidth(10);
const int Limit((256 - BandWidth)/2);
return (subclr < 255-Limit) && (subclr > Limit);
}
相似色的設計
const COLORREF ColorRef::Shift(int shift) const
{
const int r = (R() < shift)?(R() + shift):(R() - shift);
const int g = (G() < shift)?(G() + shift):(G() - shift);
const int b = (B() < shift)?(B() + shift):(B() - shift);
return RGB(r, g, b);
}