ASP.Net/Development/Color

Материал из .Net Framework эксперт
Версия от 11:51, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Color table (C#)

       
<%--
Pro ASP.NET Web Forms Techniques, Second Edition
By Alex Homer
ISBN: 1-59059-317-0
Published: Dec 2003
Publisher: Apress.ru
--%>          
       
<%@Page Language="C#" %>
<%@Import Namespace="System.Drawing" %>
<%@Import Namespace="System.Drawing.Imaging" %>
<%@Import Namespace="System.Data" %>
<script runat="server">
void Page_Load() {
  Response.ContentType="image/gif";
  String sCaption = "Chart caption";
  DrawPieChart(GetDataSet(), 420, 250, sCaption);
}
void DrawPieChart(DataSet dsData, int iWidth, int iHeight, String sCaption) {
  Bitmap oBitMap = new Bitmap(iWidth, iHeight);
  Graphics oGraphics = Graphics.FromImage(oBitMap);
  Pen oPen = new Pen(Color.Black, 1);
  SolidBrush oBrush = new SolidBrush(Color.White);
  oGraphics.FillRectangle(oBrush, 0, 0, oBitMap.Width,
                          oBitMap.Height);
  DrawText(oGraphics, 0, 0, oBitMap.Width, 20, sCaption,
           FontStyle.Bold, 10, "", StringAlignment.Center, 0);
  Color[] aColors = GetColorArray();
  int iCaptionHeight = 30;
  int iPieTopOffset = iCaptionHeight;
  int iPieDiameter = oBitMap.Height - iCaptionHeight - 6;
  if (iPieDiameter > (oBitMap.Width * 0.6)) {
    iPieDiameter = (int)(oBitMap.Width * 0.6);
    iPieTopOffset = ((oBitMap.Height - iPieDiameter) / 2) + iCaptionHeight;
  }
  Rectangle oRectPie = new Rectangle(0, iPieTopOffset,
                                iPieDiameter, iPieDiameter);
  Rectangle oRectShadow = new Rectangle(5, iPieTopOffset + 5,
                                iPieDiameter, iPieDiameter);
  // create color for shadows to objects
  Color cShadow = Color.FromArgb(153, 153, 153);
  // set brush color and draw circle for shadow
  oBrush.Color = cShadow;
  oGraphics.FillEllipse(oBrush, oRectShadow);
  // get reference to collection of data rows
  DataRowCollection colRows = dsData.Tables[0].Rows;
  // calculate left positin of "value key" boxes
  int iKeyBoxLeft = iPieDiameter + 45;
  // calculate vertical spacing for "value key" boxes
  int iKeyBoxSpace = (oBitMap.Height - iCaptionHeight - 15) / (colRows.Count - 1);
  // declare variables we"ll need
  DataRow oRow;              // reference to data row
  int iRowIndex = 0;         // index for current row
  float fSliceStart = 0;     // start degrees of slice
  float fSliceDegrees;       // number of degrees for slice
  int iKeyBoxTop;            // vertical offset of "key" box
  Double fTotalValue = 0;    // total of all values in table
  // variables to hold values extracted from rows
  String sSliceCaption;
  Double fSliceValue;
  // calculate total of all values in data table
  // iterate through the rows in the table
  foreach (DataRow oERow in colRows) {
    try {
      fTotalValue += (Double)oERow[1];
    }
    catch {}
  }
  // now ready to draw the pie chart itself
  // iterate through the rows in the table again
  foreach (DataRow oERow in colRows) {
    // calculate vertical position of "key" box
    iKeyBoxTop = iCaptionHeight + (iKeyBoxSpace * iRowIndex);
    // draw shadow for "key" box
    oBrush.Color = cShadow;
    oGraphics.FillRectangle(oBrush, iKeyBoxLeft + 3, iKeyBoxTop + 3, 15, 14);
    // get values from data row
    try {
      sCaption = (String)oERow[0];
      fSliceValue = (Double)oERow[1];
    }
    catch {
      sCaption = "Error";
      fSliceValue = 0;
    }
    // convert to number of degrees for this value
    fSliceDegrees = (float)((fSliceValue / fTotalValue) * 360);
    // set brush color from array of colors
    oBrush.Color = aColors[iRowIndex];
    // draw filled pie slice and then outline in black
    oGraphics.FillPie(oBrush, oRectPie, fSliceStart, fSliceDegrees);
    oGraphics.DrawPie(oPen, oRectPie, fSliceStart, fSliceDegrees);
    // draw filled "key" rectangle and then outline in black
    oGraphics.FillRectangle(oBrush, iKeyBoxLeft, iKeyBoxTop, 15, 14);
    oGraphics.DrawRectangle(oPen, iKeyBoxLeft, iKeyBoxTop, 15, 14);
    // draw caption text next to "key" box
    DrawText(oGraphics, iKeyBoxLeft + 22, iKeyBoxTop,
             oBitMap.Width - iKeyBoxLeft + 22, 14, sCaption,
             FontStyle.Bold, 9, "", null, 0);
    // save start position for next slice and increment row index
    fSliceStart += fSliceDegrees;
    iRowIndex += 1;
  }
  // write bitmap to response
  oBitMap.Save(Response.OutputStream, ImageFormat.Gif);
  oBitMap.Save(MapPath("piechart.gif"), ImageFormat.Gif);
  // dispose of objects
  oPen.Dispose();
  oBrush.Dispose();
  oGraphics.Dispose();
  oBitMap.Dispose();
}
// -------------------------------------------------------------------
// routine to draw text string in rectangle on bitmap
void DrawText(Graphics oGraphics, int iTop, int iLeft, int iWidth,
             int iHeight, String sText, object eFontStyle,
             int iFontSize, String sColor, object eAlign,
             StringFormatFlags eFlag) {
  // set default values if not specified
  if (eFontStyle == null) eFontStyle = FontStyle.Regular;
  if (iFontSize == 0) iFontSize = 8;
  if (sColor == "") sColor = "Black";
  if (eAlign == null) eAlign = StringAlignment.Near;
  // create the rectange to hold the text
  RectangleF oRect = new RectangleF(iTop, iLeft, iWidth, iHeight);
  // create a Font object for the text style
  Font oFont = new Font("Arial", iFontSize, (FontStyle)eFontStyle);
  // create the format object to define the format and style
  StringFormat oFormat = new StringFormat(eFlag);
  oFormat.Alignment = (StringAlignment)eAlign;      // horizontal alignment
  // always center vertically within rectangle area
  oFormat.LineAlignment = StringAlignment.Center;
  // create a brush object and draw the text
  SolidBrush oBrush = new SolidBrush(Color.FromName(sColor));
  oGraphics.DrawString(sText, oFont, oBrush, oRect, oFormat);
}
// -------------------------------------------------------------------
Color[] GetColorArray() {
  // declare an Array for 20 colors
  Color[] aColors = new Color[20];
  // fill the array of colors for chart items
  // use browser-safe colors (multiples of #33)
  aColors[0] = Color.FromArgb(204, 0, 0);      // red
  aColors[1] = Color.FromArgb(255, 153, 0);    // orange
  aColors[2] = Color.FromArgb(255, 255, 0);    // yellow
  aColors[3] = Color.FromArgb(0 ,255, 0);      // green
  aColors[4] = Color.FromArgb(0, 255, 255);    // cyan
  aColors[5] = Color.FromArgb(51, 102, 255);   // blue
  aColors[6] = Color.FromArgb(255, 0, 255);    // magenta
  aColors[7] = Color.FromArgb(102, 0, 102);    // purple
  aColors[8] = Color.FromArgb(153, 0, 0);      // dark red
  aColors[9] = Color.FromArgb(153, 153, 0);    // khaki
  aColors[10] = Color.FromArgb(0, 102, 0);     // dark green
  aColors[11] = Color.FromArgb(51, 51, 102);   // dark blue
  aColors[12] = Color.FromArgb(102, 51, 0);    // brown
  aColors[13] = Color.FromArgb(204, 204, 204); // light gray
  aColors[14] = Color.FromArgb(0, 0, 0);       // black
  aColors[15] = Color.FromArgb(102, 204, 255); // sky
  aColors[16] = Color.FromArgb(255, 204, 255); // pink
  aColors[17] = Color.FromArgb(255, 255, 204); // chiffon
  aColors[18] = Color.FromArgb(255, 204, 204); // flesh
  aColors[19] = Color.FromArgb(153, 255, 204); // pale green
  return aColors;
}
// -------------------------------------------------------------------
// function to create a DataSet containing a few values
DataSet GetDataSet() {
  // create a new DataSet object and a new table
  DataSet dsResult = new DataSet();
  DataTable tblData = new DataTable("Data");
  dsResult.Tables.Add(tblData);
  // define two columns (fields) within the table
  tblData.Columns.Add("Caption", System.Type.GetType("System.String"));
  tblData.Columns.Add("Value", System.Type.GetType("System.Double"));
  // declare a variable to hold a DataRow object
  // fill in the values and add to table then repeat
  DataRow oRow = tblData.NewRow();
  oRow["Caption"] = "Wrampant 1.6 16V";
  oRow["Value"] = 277;
  tblData.Rows.Add(oRow);
  oRow = tblData.NewRow();
  oRow["Caption"] = "Wrampant 2.0i 16V";
  oRow["Value"] = 381;
  tblData.Rows.Add(oRow);
  oRow = tblData.NewRow();
  oRow["Caption"] = "Wranger 2.5 D V6";
  oRow["Value"] = 63;
  tblData.Rows.Add(oRow);
  oRow = tblData.NewRow();
  oRow["Caption"] = "Wranger 3.2 D V6";
  oRow["Value"] = 158;
  tblData.Rows.Add(oRow);
  oRow = tblData.NewRow();
  oRow["Caption"] = "Wranger 4.8 V8";
  oRow["Value"] = 106;
  tblData.Rows.Add(oRow);
  oRow = tblData.NewRow();
  oRow["Caption"] = "Wregal 2.8 V6";
  oRow["Value"] = 63;
  tblData.Rows.Add(oRow);
  oRow = tblData.NewRow();
  oRow["Caption"] = "Wregal 3.2 D V6";
  oRow["Value"] = 19;
  tblData.Rows.Add(oRow);
  oRow = tblData.NewRow();
  oRow["Caption"] = "Wresponse 2.8 V6";
  oRow["Value"] = 28;
  tblData.Rows.Add(oRow);
  oRow = tblData.NewRow();
  oRow["Caption"] = "Wresponse 4.8 V8";
  oRow["Value"] = 42;
  tblData.Rows.Add(oRow);
  oRow = tblData.NewRow();
  oRow["Caption"] = "Wroadster 6.2 V12";
  oRow["Value"] = 17;
  tblData.Rows.Add(oRow);
  return dsResult;   // return DataSet
}
// -------------------------------------------------------------------
</script>



ColorTranslator.FromHtml

<%@ Page Language="C#"  %>
<%@Import namespace="System.Collections"%>
<%@Import namespace="System.Drawing"%>
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
  Hashtable myHash=new Hashtable();
  myHash.Add("Red", "#FF0000");
  myHash.Add("Green", "#00FF00");
  myHash.Add("Blue", "#0000FF");
  MyLabel.BackColor=ColorTranslator.FromHtml(myHash["Blue"].ToString());
  MyLabel.ForeColor=ColorTranslator.FromHtml(myHash["Red"].ToString());
  myHash=null;
}
</script>
<HTML>
  <body>
    <form id="form1" method="post" runat="server">
      <asp:Label ID="MyLabel" Runat="server">Sample Text</asp:Label><br>
    </form>
  </body>
</HTML>



Create Color object from string (VB.net)

<%@ Page Language="VB" %>
<script runat="server">
    Dim ColorList(6) as String
    
    Sub Page_Load
      ColorList(0) = "Red"
      ColorList(1) = "Orange"
      ColorList(2) = "Yellow"
      ColorList(3) = "Green"
      ColorList(4) = "Blue"
      ColorList(5) = "Indigo"
      ColorList(6) = "Violet"
      Array.Reverse(ColorList)
      
      If Not Page.IsPostback
        Dim ColorName as String
    
        For Each ColorName in ColorList
          ddlColorList.Items.Add(ColorName)
        Next
      End If
    End Sub
    
    Sub btnSelectColor_Click(sender As Object, e As EventArgs)
      lblOutputMessage.Text = "You selected " & ddlColorList.SelectedItem.Value
      lblOutputMessage.ForeColor = _
        System.Drawing.Color.FromName(ddlColorList.SelectedItem.Text)
    End Sub
</script>
<html>
<head>
</head>
<body>
    <form runat="server">
        <p>
            Select a color from the list:<asp:DropDownList id="ddlColorList" runat="server"></asp:DropDownList>
            <asp:Button id="btnSelectColor" onclick="btnSelectColor_Click" runat="server" Text="Click here!"></asp:Button>
        </p>
        <p>
            <asp:Label id="lblOutputMessage" runat="server"></asp:Label>
        </p>
    </form>
</body>
</html>



NET Standard Color Names (C#)

<%--
Pro ASP.NET Web Forms Techniques, Second Edition
By Alex Homer
ISBN: 1-59059-317-0
Published: Dec 2003
Publisher: Apress.ru
--%>       
       
<%@Page Language="C#" %>
<%@Import Namespace="System.Drawing" %>
<script runat="server">
void Page_Load() {
  Color[] aKnownCols = new Color[168];
  KnownColor eValue;
  for (eValue = 0; eValue <= KnownColor.YellowGreen; eValue++) {
    aKnownCols[(int) eValue] = Color.FromKnownColor(eValue);
  }
  // create a table containing the .NET colors
  // declare variables, we"ll create 5 rows simultaneously
  TableRow oRow1, oRow2, oRow3, oRow4, oRow5;
  TableCell oCell;
  Color oKnown;
  String sDecimalVals, sHexVals, sKnown;
  int iCellCount = 0;
  // to create empty cell with colored background
  String sColorCell = "<font size=5>&nbsp; &nbsp; &nbsp; &nbsp;</font>";
  // create empty Table object and five Row objects
  Table oTable = new Table();
  oRow1 = new TableRow();
  oRow2 = new TableRow();
  oRow3 = new TableRow();
  oRow4 = new TableRow();
  oRow5 = new TableRow();
  // set horizontal alignment for three rows
  oRow2.HorizontalAlign = HorizontalAlign.Center;
  oRow3.HorizontalAlign = HorizontalAlign.Center;
  oRow4.HorizontalAlign = HorizontalAlign.Center;
  // iterate through array of safe colors
  foreach (Color oColor in aKnownCols) {
    iCellCount += 1;   // increment cell counter
    // create the strings showing decimal and hex RGB values
    sDecimalVals = oColor.R.ToString() + "," + oColor.G.ToString()
                 + "," + oColor.B.ToString();
    sHexVals = "#" + oColor.R.ToString("x2") + oColor.G.ToString("x2")
             + oColor.B.ToString("x2");
    sKnown = oColor.Name;
    // create a new cell, and add LiteralControl containing value
    oCell = new TableCell();
    oCell.Controls.Add(new LiteralControl(sColorCell));
    // set properties for this cell, and add to row 1
    oCell.BorderColor = Color.Black;
    oCell.BorderStyle = BorderStyle.Solid;
    oCell.BorderWidth = Unit.Pixel(1);
    oCell.BackColor = oColor;
    oRow1.Cells.Add(oCell);
    // repeat for cells containing decimal, hex and color name values
    oCell = new TableCell();
    oCell.Controls.Add(new LiteralControl(sDecimalVals));
    oRow2.Cells.Add(oCell);
    oCell = new TableCell();
    oCell.Controls.Add(new LiteralControl(sHexVals));
    oRow3.Cells.Add(oCell);
    oCell = new TableCell();
    oCell.Controls.Add(new LiteralControl(sKnown));
    oRow4.Cells.Add(oCell);
    // create cell in row 5 to provide space between color rows
    oCell = new TableCell();
    oCell.Controls.Add(new LiteralControl("&nbsp;"));
    oRow5.Cells.Add(oCell);
    // start a new row every eight values
    if ((int)(iCellCount / 8) == ((float)iCellCount / 8)) {
      oTable.Rows.Add(oRow1);
      oTable.Rows.Add(oRow2);
      oTable.Rows.Add(oRow3);
      oTable.Rows.Add(oRow4);
      oTable.Rows.Add(oRow5);
      oRow1 = new TableRow();
      oRow2 = new TableRow();
      oRow3 = new TableRow();
      oRow4 = new TableRow();
      oRow5 = new TableRow();
      oRow2.HorizontalAlign = HorizontalAlign.Center;
      oRow3.HorizontalAlign = HorizontalAlign.Center;
      oRow4.HorizontalAlign = HorizontalAlign.Center;
    }
  }
  ctlPlaceholder.Controls.Add(oTable);
}
</script>
<html>
<head>
<title>.NET Standard Color Names</title>
</head>
<body>
<span class="heading">.NET Standard Color Names</span><p />
<asp:PlaceHolder id="ctlPlaceholder" runat="server" />
</body>
</html>